淺談Angular HttpClient簡(jiǎn)單入門
現(xiàn)代瀏覽器支持使用兩種不同的 API 發(fā)起 HTTP 請(qǐng)求:XMLHttpRequest 接口和 fetch() API。
@angular/common/http 中的 HttpClient 類為 Angular 應(yīng)用程序提供了一個(gè)簡(jiǎn)化的 API 來實(shí)現(xiàn) HTTP 客戶端功能。
一、準(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ī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Angular2中constructor和ngOninit的使用講解
這篇文章主要介紹了Angular2中constructor和ngOninit的使用講解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-05-05測(cè)試IE瀏覽器對(duì)JavaScript的AngularJS的兼容性
這篇文章主要介紹了測(cè)試IE瀏覽器對(duì)JavaScript的AngularJS的兼容性的方法,盡管隨著Windows10的近期上市,IE瀏覽器即將成為歷史...需要的朋友可以參考下2015-06-06