在 Angular6 中使用 HTTP 請(qǐng)求服務(wù)端數(shù)據(jù)的步驟詳解
第一步
準(zhǔn)備好api接口地址, 例如 https://api.example.com/api/
第二步
在根組件 app.components.ts 中引入 HttpClientModule 模塊。
// app.components.ts import {HttpClientModule} from "@angular/common/http"; //引入HttpClientModule 模塊 imports: [ BrowserModule, AppRoutingModule, HttpClientModule //聲明HTTP模塊 ],
第三步
在組件中使用HTTP模塊向遠(yuǎn)程服務(wù)器請(qǐng)求數(shù)據(jù)
1.引入HTTP模塊
// list.components.ts import { HttpClient } from "@angular/common/http" //這里是HttpClient
2.在組件的構(gòu)造函數(shù)中實(shí)例化 HttpClient
constructor(private http:HttpClient){}
3.創(chuàng)建用來(lái)接收數(shù)據(jù)的變量
public anyList:any
4.通過(guò)HTTP的get方法請(qǐng)求數(shù)據(jù)
ngOnInit() { //這個(gè)是初始化 this.http.get("https://api.example.com/api/list") .subscribe(res=>{ this.anyList = res }) } // get方法中接收的是一個(gè)接口文件的地址,它會(huì)接收接口傳遞過(guò)來(lái)的數(shù)據(jù),并默認(rèn)處理為json數(shù)據(jù)。 // subscribe方法是對(duì)get接收的數(shù)據(jù)進(jìn)行處理。參數(shù) res 就是接收過(guò)來(lái)的數(shù)據(jù)對(duì)象。然后把 res 對(duì)象賦值給anyList變量。
5:前臺(tái)輸出
// list.component.html <ul *ngFor="let v of anyList"> 循環(huán)輸出anyList對(duì)象數(shù)據(jù) <a routerLink="/post/{{v.id}}"> 這里的routerLink是angular的a鏈接形式 <img src="{{v.thumb}}" alt=""> 這里的v.thumb是調(diào)用anyList對(duì)象的每條數(shù)據(jù)的thumb縮略圖 <h3>{{v.name}}</h3> </a> </ul>
打開(kāi)前臺(tái)頁(yè)面,就可以看到輸出的數(shù)據(jù)信息了。
總結(jié)
以上所述是小編給大家介紹的在 Angular6 中使用 HTTP 請(qǐng)求服務(wù)端數(shù)據(jù)的步驟詳解,希望對(duì)大家有所幫助,如果大家有任何疑問(wèn)請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)腳本之家網(wǎng)站的支持!
相關(guān)文章
在Angular中如何監(jiān)聽(tīng)某個(gè)值的變化
這篇文章主要介紹了在Angular中如何監(jiān)聽(tīng)某個(gè)值的變化問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-03-03AngularJs Understanding the Controller Component
本文主要介紹AngularJs Understanding the Controller Component的內(nèi)容,這里整理了相關(guān)資料,及簡(jiǎn)單示例代碼,有興趣的小伙伴可以參考下2016-09-09解決angularjs service中依賴注入$scope報(bào)錯(cuò)的問(wèn)題
今天小編就為大家分享一篇解決angularjs service中依賴注入$scope報(bào)錯(cuò)的問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-10-10angular2路由之routerLinkActive指令【推薦】
這篇文章主要介紹了angular2路由之routerLinkActive指令的相關(guān)資料,需要的朋友可以參考下2018-05-05詳解angularjs跨頁(yè)面?zhèn)鲄⒂龅降囊恍﹩?wèn)題
這篇文章主要介紹了詳解angularjs跨頁(yè)面?zhèn)鲄⒂龅降囊恍﹩?wèn)題,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2018-11-11詳解angularjs popup-table 彈出框表格指令
本篇文章主要介紹了angularjs popup-table 彈出框表格指令,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2017-09-09AngularJS基于provider實(shí)現(xiàn)全局變量的讀取和賦值方法
這篇文章主要介紹了AngularJS基于provider實(shí)現(xiàn)全局變量的讀取和賦值方法,結(jié)合實(shí)例形式分析了AngularJS全局變量的聲明、賦值、讀取等相關(guān)使用技巧,需要的朋友可以參考下2017-06-06