最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Angular 數(shù)據(jù)請求的實(shí)現(xiàn)方法

 更新時間:2018年05月07日 14:45:22   作者:hanekaoru''s Blog  
本篇文章主要介紹了Angular 數(shù)據(jù)請求的實(shí)現(xiàn)方法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧

使用 Angular 請求數(shù)據(jù)的時候,需要引入 HttpModule 模塊,如果使用的 jsonp 模式的話,則需要另外引入 JsonpModule 模塊

import { HttpModule, JsonpModule } from '@angular/http'

然后在當(dāng)前模塊中的 imports 內(nèi)進(jìn)行注冊

imports: [
 HttpModule,
 JsonpModule
],

注冊以后就可以在組件文件當(dāng)中引入相對應(yīng)的方法來進(jìn)行數(shù)據(jù)請求了

import { Http, Jsonp } from '@angular/http'

然后在當(dāng)前組件的構(gòu)造函數(shù)當(dāng)中進(jìn)行注入以后就可以使用了

constructor(private http: Http, private jsonp: Jsonp) { }

使用如下,一個簡單的 get 請求

// 進(jìn)行注入,拿到相對應(yīng)的方法
constructor(private http: Http, private jsonp: Jsonp) { }
public list: any = []
// 請求數(shù)據(jù)
getData() {
 let url = 'http://www.phonegap100.com/appapi.php?a=getPortalList&catid=20&page=1'
 let _this = this
 this.http.get(url).subscribe((data) => {
  _this.list = JSON.parse(data['_body'])['result']
  console.log(_this.list)
 })
}

前臺進(jìn)行渲染即可

<button (click)="getData()">get 請求數(shù)據(jù)</button>
<ul>
 <li *ngFor="let item of list">
  {{item.title}}
 </li>
</ul>

JSONP 請求數(shù)據(jù)

注意區(qū)分與 get 請求的區(qū)別,使用如下

// 請求數(shù)據(jù)
jsonpData() {
 let url = 'http://www.phonegap100.com/appapi.php?a=getPortalList&catid=20&page=1&callback=JSONP_CALLBACK'
 let _this = this
 this.jsonp.get(url).subscribe((data) => {
  _this.list = data['_body']['result']
  console.log(_this.list)
 })
}
// 渲染
<button (click)="jsonpData()">jsonp 請求數(shù)據(jù)</button>
<ul>
 <li *ngFor="let item of list">
  {{item.title}}
 </li>
</ul>

不同點(diǎn)

請求的 url 參數(shù)結(jié)尾必須要添加指定的回調(diào)函數(shù)名稱 &callback=JSONP_CALLBACK

請求的方式變?yōu)?this.jsonp.get(url)

請求后得到的數(shù)據(jù)格式不統(tǒng)一,需要自行進(jìn)行調(diào)整

POST 請求

與 GET 的請求方式有些許不同,首先需要引入請求頭 { Headers }

import { Http, Jsonp, Headers } from '@angular/http'

然后來對請求頭進(jìn)行定義,需要先實(shí)例化 Headers

private headers = new Headers({'Content-Type': 'application/json'})

最后在提交數(shù)據(jù)的時候帶上 Headers 即可

postData() {
 let url = 'http://localhost:8080/login'
 let data = {
  "username": "zhangsan",
  "password": "123"
 }
 this.http.post(
  url,
  data,
  {headers: this.headers}
 ).subscribe((data) => {
  console.log(data)
 })
}

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評論

永和县| 青阳县| 翁牛特旗| 黑龙江省| 耒阳市| 韶山市| 峨山| 天门市| 星座| 安多县| 长沙市| 太原市| 百色市| 南康市| 玉林市| 芷江| 东乌珠穆沁旗| 贡觉县| 衡阳市| 淮北市| 金川县| 衡阳县| 苏尼特右旗| 舒兰市| 广元市| 全南县| 丰台区| 仁化县| 洛浦县| 托克托县| 齐河县| 屏边| 江西省| 蓝山县| 新巴尔虎右旗| 普兰店市| 新密市| 淮阳县| 新巴尔虎右旗| 车险| 酉阳|