angular 中使用 http 請求的前提,需要引入 httpClientModule 模塊
根模塊中 app.module.ts:
import { HttpClientModule } from '@angular/common/http'
imports: [
BrowserModule,
AppRoutingModule,
HttpClientModule
],
組件中:
import { HttpClient} from '@angular/common/http'
constructor(public http: HttpClient) { }
1. GET 請求寫法:
getData() {
let url = '/search/interface/getrelatequery?word=%E6%99%8B%E6%B1%9F'
this.http.get(url).subscribe((res: any)=>{
console.log("GET 請求", res)
this.newsList = res.data.relateQuery
})
}
2. POST 請求寫法:
post 請求必須設置請求頭
import { HttpClient, HttpHeaders } from '@angular/common/http'
postData() {
let api = '/api/message/readnotice'
let requestData = {
advert_id: '212'
}
let headerOption = { headers: new HttpHeaders({ "Content-Type": 'application/json'})}
this.http.post(api, requestData, headerOption).subscribe((res)=>{
console.log("POST請求:", res)
})
}
3. jsonp 請求:
jsonp 請求與前兩種不同之處在與,除了引入 httpClientModule 之外,還要引入 HttpClientJsonpModule
根模塊中:
import { HttpClientModule, HttpClientJsonpModule } from '@angular/common/http'
組件中:
如果不引入 HttpClientJsonModule , this.http.jsonp 報錯
/**
* jsonp 解決跨域
* 使用 JSONP 格式請求數據的前提是 后台必須支持 jsonp 請求, 請求的 api 中帶有 callBack 或者 cb
*/
getJsonpData() {
let url = '/search/interface/getrelatequery?word=%E6%99%8B%E6%B1%9F'
this.http.jsonp(url, 'callback').subscribe((res)=>{
console.log("JSOP 請求數據", res)
})
}