我的网站有这个配置:
import { InjectionToken } from '@angular/core';
import { HttpHeaders } from '@angular/common/http';
export let APP_CONFIG = new InjectionToken<IAppConfig>('app.config');
export interface IAppConfig {
apiEndpoint: string;
headersOptions: HttpHeaders;
}
export const AppConfig: IAppConfig = {
apiEndpoint: 'https://localhost:44354/',
headersOptions : new HttpHeaders({ 'Content-Type': 'application/json' }),
};
我需要使用core.module
来使用config
:
@NgModule({
declarations: [],
imports: [
CommonModule,
ToastrModule.forRoot()
],
exports: [],
providers: [
{
provide: APP_CONFIG,
useValue: AppConfig,
multi: true
},
{
provide: HTTP_INTERCEPTORS,
useClass: RequestInterceptor, multi: true
}
],
})
export class CoreModule {
constructor( @Optional() @SkipSelf() core: CoreModule) {
if (core) {
throw new Error("CoreModule should be imported ONLY in AppModule.");
}
}
}
我在 app.module
中使用 core.module
。
这是我的app.module
:
@NgModule({
declarations: [
AppComponent,
TopHeaderComponent
],
imports: [
BrowserModule,
HttpClientModule,
SharedModule,
ReactiveFormsModule,
AppRoutingModule,
ToastrModule.forRoot(),
BrowserAnimationsModule,
FormsModule,
CoreModule,
NgZorroAntdModule
],
providers:[{ provide: NZ_I18N, useValue: en_US }],
bootstrap: [AppComponent]
})
export class AppModule { }
现在我需要在我的服务中使用AppConfig
:
constructor(httpClient: HttpClient, @Inject(APP_CONFIG) private appConfig: IAppConfig) {
super(httpClient);
}
但它向我显示了这个错误:
Uncaught (in promise): NullInjectorError: StaticInjectorError(AppModule)[[object Object]]:
有什么问题吗?我该如何解决这个问题???
最佳答案
修改您的核心模块,如下所示(删除 multi: true
)
@NgModule({
declarations: [],
imports: [
CommonModule,
ToastrModule.forRoot()
],
exports: [],
providers: [
{
provide: APP_CONFIG,
useValue: AppConfig //multi: true -> Remove here
},
{
provide: HTTP_INTERCEPTORS,
useClass: RequestInterceptor,
multi: true
}
],
})
export class CoreModule {
constructor( @Optional() @SkipSelf() core: CoreModule) {
if (core) {
throw new Error("CoreModule should be imported ONLY in AppModule.");
}
}
}
然后您可以按如下方式注入(inject)您的服务:
@Injectable()
export class MainService {
constructor(@Inject(APP_CONFIG) private appConfig: IAppConfig) { }
getEndPoint(): string {
alert(this.appConfig.apiEndpoint);
return this.appConfig.apiEndpoint;
}
}
关于javascript - 将我的站点配置注入(inject)到 Angular 8 的其他模块中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58660740/