如何在ionic2中进行http GET / POST请求 什么是需要导入的数据? 我试过HTTP GET request in JavaScript?,但它对我不起作用。
答案 0 :(得分:0)
获取示例
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/
祝你好运。答案 1 :(得分:0)
首先,我们需要使用以下命令添加提供程序: -
$ 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