简体   繁体   中英

Angular Pass HttpClient from app.module to another module to a service

I am developing an Angular (ngx-*) NPM Package. I have it compiled properly, and am using it in a new fresh project using npm link

The service has the following constructor to inject HttpClient and settings.

Updated.

MyService

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

MyService.Module

I have the following for root in the module

    @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.

@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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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