Home > Enterprise >  HttpClient vs HttpClientModule as parameters in Angular components
HttpClient vs HttpClientModule as parameters in Angular components

Time:07-07

Trying to use this article (among others) to get my first Angular program to run. I am trying to get my service to use HttpClient, but neither passing in the interface to my new service, an instance of HttpClient to the service's constructor, nor an instance of HttpClientModule to the service's constructor seems to work

// from app.component.ts
export class AppComponent {
  client = new HttpClientModule();

  service = new CharactersheetService(this.client);  
  //Argument of type 'HttpClientModule' is not assignable to parameter of type 'HttpClient'.
  //contructor(private myService : ICharacterSheetService) {};  // Also generates errors
...

// from charactersheet.service.ts
@Injectable({
  providedIn: 'root'
})
export class CharactersheetService implements ICharacterSheetService {

  constructor(private httpClient : HttpClient){};  // declaring as HttpClientModule adds more errors

  public getSheetById() { ...

I thought that importing HttpClientModule and HttpClient let you inject an instance of HttpClient in the service. What am I doing wrong?

CodePudding user response:

In your app.module.ts:

@NgModule({
   declarations: [
       // your declarations
   ],
   imports: [
       HttpClientModule,
       // the rest of your imports
   ],
   providers: [
       CharactersheetService,
      // remainder of providers
   ],
   bootstrap: [AppComponent]
})
export class AppModule{}

Now it will be available for dependancy injection in your CharactersheetService. No need to instantiate HttpClientModule, just import it into your module.

Also same goes for your CharactersheetService, since it is provided in the app module, you just need to inject it into the app.component to use it. IE:

export class AppComponent {  
 constructor(private charactersheetService: CharactersheetService) { 
 } 
}

CodePudding user response:

What you are doing wrong: you are doing too much!

Solution:

// from app.component.ts
export class AppComponent {
  constructor(charactersheetService: CharactersheetService) {}
}

// from charactersheet.service.ts
@Injectable({
  providedIn: 'root'
})
export class CharactersheetService implements ICharacterSheetService {

  constructor(private httpClient : HttpClient){}

  public getSheetById() { ... }
}

@Injectable({provideIn: 'root'}) creates a singleton of the service to be used anywhere in the app (in any other service or any component). So you simply inject that service into the components that needs it. HttpClient comes from from the HttpClientModule, so you also need to import it using the following code in AppModule:

@NgModule({
  declarations: [
    ...
  ],
  imports: [
    ...
    HttpClientModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }
  • Related