如何在ionic2中http http GET / POST请求以及需要导入的数据是什么? 我尝试使用HTTP GET request in JavaScript?,但它对我不起作用。
获取示例
this.posts = null;
this.http.get('https://www.reddit.com/r/gifs/top/.json?limit=2&sort=hot').map(res => res.json()).subscribe(data => {
this.posts = data.data.children;
});
console.log(this.posts);
https://www.joshmorony.com/using-http-to-fetch-remote-data-from-a-server-in-ionic-2/
POST示例
let headers = new Headers();
headers.append('Content-Type', 'application/json');
let body = {
message:"do you hear me?"
};
this.http.post('http://spstest.000webhostap..., JSON.stringify(body), {headers: headers})
.map(res => res.json())
.subscribe(data => {
console.log(data);
});
}
https://www.joshmorony.com/how-to-send-data-with-post-requests-in-ionic-2/
祝好运。
要首先创建请求,我们需要使用以下命令添加提供程序: -
$ ionic g provider restService
这里的restService是ts文件名,我们在其中编写以下代码来发出请求
load() {
console.log(' RestServiceProvider Load Method fro listing');
let postParams = { param1 : '', param2: '' }
if (this.data) {
return Promise.resolve(this.data);
}
// don't have the data yet
return new Promise(resolve => {
this.http.post("YOUR URL", postParams)
.map(res => res.json())
.subscribe(data => {
this.data = data;
resolve(this.data);
});
});
}
在上面的代码中,load()是restService类的方法。这个方法有助于发出请求。这个方法在你的其他类中被调用。
this.restSrvProvider.load().then(data => {
let mydata = data;
});
如需更多知识,您可以通过ionic blog