我有使用TranslateModule
from的模块ngx-translate
(问题不是关于这个库,而是关于Angular)。看起来像这样:
@NgModule({ ... imports: [ TranslateModule.forChild({ loader: { provide: TranslateLoader, useFactory: (http: HttpClient) => new TranslateHttpLoader(http, './assets/i18n/todos/', '.json'), deps: [HttpClient] }, isolate: true }) ] }) export class TodosModule { }
现在有5个看起来像这样的模块。我决定搬家TranslateModule
到SharedModule
。但这是一个问题:我必须为每个模块分别设置路径(例如./assets/i18n/todos
)。那就是我发现的:
@NgModule({ ... imports: [ TranslateModule ], exports: [ TranslateModule ] }) export class SharedModule { static forChild(i18path: string): ModuleWithProviders { return { ngModule: SharedModule, providers: [ { provide: TranslateModule, useValue: TranslateModule.forChild({ loader: { provide: TranslateLoader, useFactory: (http: HttpClient) => new TranslateHttpLoader(http, `./assets/i18n/${i18nPath}/`, '.json'), deps: [HttpClient] }, isolate: true }) } ] } } }
但这是行不通的。TranslateHttpLoader
不加载翻译文件。控制台中没有错误。我究竟做错了什么?
我找到了解决方案。我不得不进口TranslateModule.forChild(...)
到SharedModule
,但提供TranslateLoader
的内部SharedModule#forChild
方法:
@NgModule({ imports: [ CommonModule, HttpClientModule, TranslateModule.forChild({ isolate: true }) ], exports: [ TranslateModule ] }) export class SharedModule { static forChild(i18nPath: string): ModuleWithProviders { return { ngModule: SharedModule, providers: [ { provide: TranslateLoader, useFactory: (http: HttpClient) => new TranslateHttpLoader(http, `./assets/i18n/${i18nPath}/`, '.json'), deps: [HttpClient] } ] } } }