- 在app.module.ts中引入HttpClientModule(HttpClient的服务提供者),以便全局注册 Angular 的
HttpClient
。
import { HttpClientModule } from ‘@angular/common/http‘;
@NgModule({
imports: [
HttpClientModule //导入
],
declarations: [
],
bootstrap: [
AppComponent
]
})
export class AppModule { }
- 在需要的组件中注入httpClient
import { HttpClient } from ‘@angular/common/http‘; export class CartService { constructor( private http: HttpClient ) {} }
- http正确使用方法:
1、在service中写入http方法
2、在component中写入substribe方法,如下:
在apiService中:
function getData(){
this.http.get(this.url,{header});
}
在component导入service
this.apiService.getData().substribe(res=>{
console.log(res);
})
-
ps:Angular httpClient获取请求头信息
const headers = new HttpHeaders(environment.otherRequestHeaders);const httpOptions = {headers: headers,responseType: ‘json‘ as ‘json‘,};this.http.get(url,httpOptions).subscribe(res=>{console.log(res);});