在我的角度应用程序中,组件之一从服务模块(app.service.ts)调用一个方法,该模块使用HttpClient模块以基本auth('username':'password')调用其余api,使用'HttpHeaders'模块来设置标题,如下所示:
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(平台:核心)[ApiService-> HttpHeaders]:NullInjectorError:HttpHeaders没有提供者!
所以,我将'HttpHeaders'包含在app.modules.ts中,并将其添加到了导入部分:
import { HttpClientModule,HttpHeaders } from '@angular/common/http';
imports: [
HttpClientModule,
HttpHeaders
]
现在静态注入已解决,但是捕获了未捕获的错误:
由模块'AppModule'导入的意外值'HttpHeaders'。请添加@NgModule批注。
如何在angular8中调用rest api,它的标题中需要基本的auth?
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
]