1

我知道这个问题类似于Angular 6 custom lib No provider for ComponentFactoryResolver

错误:StaticInjectorError(AppModule)[AppComponent -> NgRestModelService]: StaticInjectorError(Platform: core)[AppComponent -> NgRestModelService]: NullInjectorError: No provider for NgRestModelService!

要查看完整代码,请访问 GitHub 上的存储库

我遵循了Angular 的文档(和Angular 的示例代码),但是显示了这个错误。

简而言之:有一个服务应该配置 API 的基本 URL,但配置没有提供给服务的构造函数,即使它存在于forRoot()NgModule 的方法中。

应用模块:

@NgModule({
    declarations: [
        AppComponent
    ],
    imports: [
        BrowserModule,
        HttpClientModule,
        NgRestModelModule.forRoot({
            baseUrl: 'http://localhost:5656/api'
        }),
    ],
    providers: [Denomination],
    bootstrap: [AppComponent]
})
export class AppModule {}

库模块:

@NgModule({
    imports: [],
    declarations: [],
    exports: [],
    providers: [NgRestModelService]
})
export class NgRestModelModule {
    static forRoot(config: INgRestModelConfig): ModuleWithProviders {
        console.log('forRoot got ', config);
        return {
            ngModule: NgRestModelModule,
            providers: [
                {provide: NgRestModelConfig, useValue: config}
            ]
        };
    }

    constructor(@Optional() @SkipSelf() parentModule: NgRestModelModule) {
        if (parentModule) {
            throw new Error(
                'NgRestModelModule is already loaded. Import it in the AppModule only');
        }
    }
}

库服务:

export class NgRestModelConfig implements INgRestModelConfig {
    http: HttpClient;
    baseUrl: string;
}

@Injectable()
export class NgRestModelService {

    // ...

    constructor(
        private _http: HttpClient,
        @Optional() config: NgRestModelConfig,
    ) {
        console.log('consturcting NgRestModelService, config: ', config);
        if (config) {
            this.configure(config);
        }
    }

    // ...

}
4

0 回答 0