首页 > 解决方案 > Angular 将 HttpClient 从 app.module 传递到另一个模块到服务

问题描述

我正在开发一个 Angular (ngx-*) NPM 包。我已经正确编译它,并在一个新的新项目中使用它npm link

该服务具有以下构造函数来注入 HttpClient 和设置。

更新。

我的服务

  constructor(private http: HttpClient, @Inject('configs') configs: ImyConfigs) {

我的服务模块

我在模块中有以下根目录

    @NgModule({

      declarations: [
      ],
      imports: [
        CommonModule,
 // note that I am not importing HttpClientModule
 // My understanding is that if I do I will get duplicate issues?
      ],
      exports: [],
      providers: []
    })
    export class MyModule {
          static forRoot(configs?: ImyConfigs): ModuleWithProviders {
            return {
              ngModule: MyModule,
              providers: [MyService, { provide: 'configs', useValue: configs }]
            };
          }

应用模块

现在在我的主项目(使用此模块的新 Angular 项目)中,我想使用此服务。

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    HttpClientModule,
    MyModule.forRoot(MYCONFIG_CONST)    

  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

我不断收到以下错误:

ERROR Error: StaticInjectorError(AppModule)[MyService -> HttpClient]: 
  StaticInjectorError(Platform: core)[MyService -> HttpClient]: 
    NullInjectorError: No provider for HttpClient!

关于将 HttpClient 注入 myService,我做错了什么?

编辑:我将在下面回答。

标签: javascriptangular

解决方案


ng serve  --preserve-symlinks

解决了这个问题。

这是一个旧项目,它已经添加到 package.json 中,我只是忘记了它 - for ... to long。


推荐阅读