静态注入错误或 Please add a @NgModule annotation error from angular

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

在我的 angular 应用程序中,其中一个组件从服务模块 (app.service.ts) 调用方法,该方法使用 'HttpClient' 模块调用其余 api basic auth('username':'password'),我使用 'HttpHeaders' 模块来设置 headers 如下:

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});
  }
}

静态注入错误如下:

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

所以,我将 'HttpHeaders' 包含在 app.modules.ts 中并将其添加到导入部分:

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

现在静态注入已解决,但捕获了一个未捕获的错误:

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

如何在 angular8 中调用 rest api,这将需要在其 headers 中进行基本身份验证?

HttpHeaders 不是模块,也不应该注入。只需将其导入您的服务并使用 new HttpHeaders() 创建一个新实例。 它应该是这样的:

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
]