我面临同样的问题,并找到了解决方法。
我决定在资产文件夹中发布角度语言环境数据(来自 cldr)。Cldr 数据来自 node_mopdules\@angular\common\locales (您将在 typescript 中导入的内容)。就在引导之前,使用 APP_INITIALIZER,我从给定特定 locale_id 的资产中加载当前文化数据。
诀窍是避免使用import
关键字,因为 EC2015 不支持动态导入。为了从 js 文件中获取文化数据,我编写了这个“脏”代码:
import { Injectable, Inject, LOCALE_ID } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable()
export class LoaderService {
constructor(protected httpClient: HttpClient,
@Inject(LOCALE_ID) protected locale: string) { }
private async loadAngularCulture(locale) {
let angularLocaleText = await this.httpClient.get(`assets/angular-locales/${locale}.js`).toPromise();
// extracting the part of the js code before the data,
// and i didn't need the plural so i just replace plural by null.
const startPos = angularLocaleText.indexOf('export default ');
angularLocaleText = 'return ' + angularLocaleText.substring(startPos + 15).replace('plural', null);
// The trick is here : to read cldr data, i use a function
const f = new Function(angularLocaleText);
const angularLocale = f();
// console.log(angularLocale);
// And now, just registrer the object you just created with the function
registerLocaleData(angularLocale);
}
并且是我的 mainModule,使用 APP_INITIALIZER :
export function configFactory(intlLoader: SfkIntlLoaderService) {
return intlLoader.initializer();
}
export function localFunction() {
// the rule to get you language according.
// Here, for demo, i just read it from localstorage
return localStorage.getItem('LANGUGAGE');
}
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
HttpClientModule
)
],
providers: [
LoaderService,
{
provide: LOCALE_ID,
deps: [],
useFactory: localFunction
},
{
provide: APP_INITIALIZER,
useFactory: configFactory,
deps: [LoaderService],
multi: true
}
],
bootstrap: [AppComponent]
})
export class AppModule { }
希望这会有所帮助!