Javascript 在angular 8中的其他模块中插入我的站点配置
我的站点有以下配置:Javascript 在angular 8中的其他模块中插入我的站点配置,javascript,angular,typescript,Javascript,Angular,Typescript,我的站点有以下配置: 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; hea
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' }),
};
我使用app.module
中的core.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);
}
但它告诉我这个错误:
未捕获(承诺中):NullInjectorError:StaticInjectorError(AppModule)[[object]]:
有什么问题?如何解决此问题?修改核心模块,如下所示(删除
multi:true
)
然后,您可以按如下方式注入您的服务:
@Injectable()
export class MainService {
constructor(@Inject(APP_CONFIG) private appConfig: IAppConfig) { }
getEndPoint(): string {
alert(this.appConfig.apiEndpoint);
return this.appConfig.apiEndpoint;
}
}
@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.");
}
}
}
@Injectable()
export class MainService {
constructor(@Inject(APP_CONFIG) private appConfig: IAppConfig) { }
getEndPoint(): string {
alert(this.appConfig.apiEndpoint);
return this.appConfig.apiEndpoint;
}
}