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

错误:StaticInjectorError(AppModule)[AppComponent - > NgRestModelService]:StaticInjectorError(Platform:core)[AppComponent - > NgRestModelService]:NullInjectorError:没有NgRestModelService的提供者!

To see full code visit the repo on GitHub .

我已经按照documentations of Angular(和Angular's example code)但显示了此错误 .

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

应用模块:

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

Lib模块:

@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');
        }
    }
}

Lib服务:

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);
        }
    }

    // ...

}