我们想在我们的 angular-17 项目中使用 ngx-tanslate,其中我们没有模块,只有独立组件。
我们收到以下错误:
ERROR Error: NG0203: inject() must be called from an injection context such as a constructor, a factory function, a field initializer, or a function used with `runInInjectionContext`. Find more at https://angular.io/errors/NG0203
at injectInjectorOnly (core.mjs:985:15)
at ɵɵinject (core.mjs:998:42)
at ɵɵdirectiveInject (core.mjs:12042:16)
at TranslatePipe_Factory (ngx-translate-core.mjs:1050:40)
at Module.ɵɵpipe (core.mjs:28466:30)
at FooterComponent_Template (footer.component.html:21:8)
在组件模板中调用
translate
-pipe 时会抛出该错误。组件定义如下所示:
@Component({
selector: 'footer',
templateUrl: './footer.component.html',
imports: [MatButtonModule, TranslateModule],
standalone: true
})
main.ts 看起来像这样:
export function createTranslateLoader(httpClient: HttpClient) {
return new TranslateHttpLoader(httpClient);
}
bootstrapApplication(AppComponent, {
providers: [
provideHttpClient(withInterceptorsFromDi()),
...
),
importProvidersFrom(
BrowserModule.withServerTransition({ appId: 'ng-cli-universal' }),
...,
TranslateModule.forRoot({
loader: {
provide: TranslateLoader,
useFactory: createTranslateLoader,
deps: [HttpClient]
}
})
),
]
}).catch(err => console.log(err));
谁来修理?
问题是我使用
npm install @ngx-translate/core --save
安装了 ngx-tanslate,如 ngx-translate 教程中所述,但 --save
似乎导致了此错误。
我通过手动将
@ngx-translate/core
和 ../http-loader
添加到 package.json 依赖项解决了这个问题。