【发布时间】:2022-03-05 18:02:25
【问题描述】:
如何在 ionic2 中 http GET/POST 请求
需要导入哪些数据?
我尝试使用HTTP GET request in JavaScript?,但它对我不起作用。
【问题讨论】:
如何在 ionic2 中 http GET/POST 请求
需要导入哪些数据?
我尝试使用HTTP GET request in JavaScript?,但它对我不起作用。
【问题讨论】:
GET 示例
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这个
【讨论】: