現(xiàn)代瀏覽器支持使用兩種不同的 API 發(fā)起 HTTP 請(qǐng)求:XMLHttpRequest 接口和 fetch() API。
@angular/common/http 中的 HttpClient 類(lèi)為 Angular 應(yīng)用程序提供了一個(gè)簡(jiǎn)化的 API 來(lái)實(shí)現(xiàn) HTTP 客戶(hù)端功能。
一、準(zhǔn)備工作
首先在app.module.ts 導(dǎo)入 HttpClientModule。如下:
import { HttpClientModule } from '@angular/common/http'; @NgModule({ imports: [ HttpClientModule, ] }) export class AppModule {}
二、在需要引用HttpClient的service.ts中引入HttpClient,如下:
import { HttpClient } from '@angular/common/http'; export class ConfigService { constructor(private http: HttpClient) { } }
三、請(qǐng)求數(shù)據(jù)
return this.http.get/post(url:'請(qǐng)求地址' , options: { headers: this.headers }) .toPromise() .then((data: any) => { return data; }) .catch((err) => { console.log(err); }); }
四、在對(duì)應(yīng)的component.ts文件中引入service
數(shù)據(jù)格式:
{ "lists":[ {"title":"","pic":""}, {"title":"","pic":""} ] }
五、頁(yè)面上調(diào)用
相信看了本文案例你已經(jīng)掌握了方法,更多精彩請(qǐng)關(guān)注Gxl網(wǎng)其它相關(guān)文章!
推薦閱讀:
如何使用vue注冊(cè)組件
如何使用Vue.js計(jì)算屬性與偵聽(tīng)器
聲明:本網(wǎng)頁(yè)內(nèi)容旨在傳播知識(shí),若有侵權(quán)等問(wèn)題請(qǐng)及時(shí)與本網(wǎng)聯(lián)系,我們將在第一時(shí)間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com