第一步
準備好api接口地址, 例如 https://api.example.com/api/
第二步
在根組件 app.components.ts 中引入 HttpClientModule 模塊。
// app.components.tsimport {HttpClientModule} from "@angular/common/http"; //引入HttpClientModule 模塊imports: [ BrowserModule, AppRoutingModule, HttpClientModule //聲明HTTP模塊],第三步
在組件中使用HTTP模塊向遠程服務(wù)器請求數(shù)據(jù)
1.引入HTTP模塊
// list.components.tsimport { HttpClient } from "@angular/common/http" //這里是HttpClient2.在組件的構(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ù),并默認處理為json數(shù)據(jù)。// subscribe方法是對get接收的數(shù)據(jù)進行處理。參數(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)網(wǎng)站的支持!
新聞熱點
疑難解答