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