简体   繁体   English

Angular将HttpClient从app.module传递到另一个模块到服务

[英]Angular Pass HttpClient from app.module to another module to a service

I am developing an Angular (ngx-*) NPM Package. 我正在开发Angular(ngx- *)NPM软件包。 I have it compiled properly, and am using it in a new fresh project using npm link 我已经正确编译了它,并且正在使用npm link在一个新的新项目中使用它

The service has the following constructor to inject HttpClient and settings. 该服务具有以下构造函数以注入HttpClient和设置。

Updated. 更新。

MyService 我的服务

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

MyService.Module MyService.Module

I have the following for root in the module 我在模块中有以下root用户

    @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 }]
            };
          }

App.module 应用模块

Now in my main project (fresh Angular project using this module) I want to use this service. 现在在我的主项目(使用此模块的新Angular项目)中,我想使用此服务。

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

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

I keep getting the following error: 我不断收到以下错误:

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

What am I doing wrong with regards to injecting the HttpClient into myService? 关于将HttpClient注入myService,我做错了什么?

Edit: I will answer below. 编辑:我将在下面回答。

ng serve  --preserve-symlinks

Solved the problem. 解决了问题。

This is an old project and it was already added to package.json, I just forgot about it ― for ... to long. 这是一个旧项目,它已经添加到package.json中,我只是忘了它了...很长时间了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM