今天就跟大家聊聊有关怎么在Angular中实现数据请求,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。
使用 Angular 请求数据的时候,需要引入 HttpModule 模块,如果使用的 jsonp 模式的话,则需要另外引入 JsonpModule 模块
import { HttpModule, JsonpModule } from '@angular/http'
然后在当前模块中的 imports 内进行注册
imports: [
HttpModule,
JsonpModule
],
注册以后就可以在组件文件当中引入相对应的方法来进行数据请求了
import { Http, Jsonp } from '@angular/http'
然后在当前组件的构造函数当中进行注入以后就可以使用了
constructor(private http: Http, private jsonp: Jsonp) { }
使用如下,一个简单的 get 请求
// 进行注入,拿到相对应的方法
constructor(private http: Http, private jsonp: Jsonp) { }
public list: any = []
// 请求数据
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 请求数据</button>
<ul>
<li *ngFor="let item of list">
{{item.title}}
</li>
</ul>
JSONP 请求数据
注意区分与 get 请求的区别,使用如下
// 请求数据
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 请求数据</button>
<ul>
<li *ngFor="let item of list">
{{item.title}}
</li>
</ul>
不同点
请求的 url 参数结尾必须要添加指定的回调函数名称 &callback=JSONP_CALLBACK
请求的方式变为 this.jsonp.get(url)
请求后得到的数据格式不统一,需要自行进行调整
POST 请求
与 GET 的请求方式有些许不同,首先需要引入请求头 { Headers }
import { Http, Jsonp, Headers } from '@angular/http'
然后来对请求头进行定义,需要先实例化 Headers
private headers = new Headers({'Content-Type': 'application/json'})
最后在提交数据的时候带上 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)
})
}
看完上述内容,你们对怎么在Angular中实现数据请求有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注亿速云行业资讯频道,感谢大家的支持。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。