Search code examples
typescriptangular8basic-authentication

Either static Injection error or a Please add a @NgModule annotation error from angular


In my angular application, one of the component invokes a method from service module(app.service.ts) , which uses 'HttpClient' module to call the rest api with basic auth('username':'password'), i used 'HttpHeaders' module to set the headers just as below :

export class ApiService {

 constructor(private httpClient: HttpClient,private httpHeaders: HttpHeaders) {
     this.httpHeaders.set('Authorization','Basic ' + btoa('usename1:password1'));
     this.httpHeaders.append('Content-Type','application/json');
  }
  public getApiData(url:any){
    return this.httpClient.get(url,{headers:this.httpHeaders});
  }
}

a static injection error occurs as below:

StaticInjectorError[NesinfoComponent -> ApiService]: StaticInjectorError(AppModule)[ApiService -> HttpHeaders]: StaticInjectorError(Platform: core)[ApiService -> HttpHeaders]: NullInjectorError: No provider for HttpHeaders!

so, i included the 'HttpHeaders' in to app.modules.ts and added it in the imports section:

import { HttpClientModule,HttpHeaders } from '@angular/common/http';
imports: [
          HttpClientModule,
          HttpHeaders
]

now the static injection resolved,but catches an uncaught error :

Unexpected value 'HttpHeaders' imported by the module 'AppModule'. Please add a @NgModule annotation.

how to invoke a rest api in angular8 which will needs a basic auth in its headers?


Solution

  • HttpHeaders is not a module and it is not something you should be injecting. Just import it into your service and create a new instance in place with new HttpHeaders(). Here is how it should be:

    export class ApiService {
    
     constructor(private httpClient: HttpClient) {  }
      private createAuthHeaders(): HttpHeaders {
         return new HttpHeaders({
           Authorization: `Basic ${btoa('usename1:password1')}`,
           'Content-Type': 'application/json'
         });
      }
    
      public getApiData(url:any){
        const httpHeaders = this.createAuthHeaders();
        return this.httpClient.get(url,{headers: httpHeaders});
      }
    }
    
    import { HttpClientModule} from '@angular/common/http';
    imports: [
      HttpClientModule
    ]