国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 語言 > JavaScript > 正文

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

2024-05-06 15:34:32
字體:
供稿:網(wǎng)友

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

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

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

imports: [ HttpModule, JsonpModule],

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

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

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

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

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

// 進行注入,拿到相對應的方法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) })}

前臺進行渲染即可

<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>

不同點

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

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

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

POST 請求

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

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

然后來對請求頭進行定義,需要先實例化 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)容,希望對大家的學習有所幫助,也希望大家多多支持錯新站長站。

發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表

圖片精選

主站蜘蛛池模板: 富裕县| 栖霞市| 汨罗市| 嵩明县| 唐海县| 辽阳县| 钟祥市| 黎城县| 淮南市| 儋州市| 琼中| 连平县| 德化县| 菏泽市| 灵璧县| 邵阳县| 兖州市| 兴国县| 虹口区| 皮山县| 郴州市| 吐鲁番市| 三台县| 安阳市| 西吉县| 洪雅县| 娱乐| 西乌珠穆沁旗| 罗平县| 岑溪市| 吉安县| 蒙山县| 东明县| 车致| 三都| 舒兰市| 福安市| 曲水县| 阿图什市| 牡丹江市| 布拖县|