1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
| 1. 引入httpClientModule模块 import {HttpClientModule} from '@angular/common/http'; 2. 依赖注入,在app.module.ts中注入模块 @ngModule({ ... imports:[ BrowserModule, HttpClientModule ] ... }) 3. 组件内引入httpClient(作为一个服务引入,因此需要在构造方法内注入) import {HttpClient} from '@angular/common/http'; export class xxx implements OnInit{ constructor(public http:HttpClient){ ... } } 4. 请求数据 - get请求: this.http.get(apiUrl).subscribe((response)=>{ ... }) - post请求: 需要设置请求头,因此需要额外引入HttpHeaders import {HttpClient,HttpHeaders} from '@angular/common/http'; 设置请求头 const httpOptions = {headers: new HttpHeader({'content-Type':'application/json'})}; 请求数据 this.post(apiUrl,data,httpOptions).subscribe((response)=>{ ... }) 5. 对jsonp的支持 - 首先需要在app.module.ts中引入jsonp模块 HttpClientJsonpModule,并注入 import {HttpClientModule,HttpClientJsonpModule} from '@angular/common/http'; @ngModule({ ... imports:[ BrowserModule, HttpClientModule, HttpClientJsonpModule ] ... }) - 使用jsonp(必须得后台支持) this.http.jsonp(api,'callback').subscribe((response)=>{ ... })
|