离子 2 http.get() 问题 [英] Ionic 2 http.get() issue
本文介绍了离子 2 http.get() 问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我尝试使用这两种方法进行 http.get()
调用.
I tried to make a http.get()
call with these two methods.
第一:
getResults(){
return this.http.get('http://localhost/api.php')
.toPromise()
.then( data => data.json() );
}
错误显示:
3 122412 error EXCEPTION: Uncaught (in promise): Response with status:0 for URL: null
4 122413 error ORIGINAL STACKTRACE:
5 122413 error Error: Uncaught (in promise): Response with status: 0 for URL: null
..........
第二:
getResults(){
return new Promise((resolve, reject) => {
this.http.get('http://localhost/api.php')
.map(res => res.json())
.subscribe(data => {
resolve(data);
}, (err) => {
reject(err);
});
});
}
错误显示:
2 925052 error EXCEPTION: Uncaught (in promise): Response with status:0 for URL: null
3 925052 error ORIGINAL STACKTRACE:
4 925053 error Error: Uncaught (in promise): Response with status: 0 for URL: null
.......
我应该使用哪种方法,可能会出现什么问题?
Which method should I use and what could be the issue?
推荐答案
响应状态为:0 对于 URL:null
Response with status:0 for URL: null
这似乎与 CORS 问题有关...请检查您的后端代码中是否启用了 CORS.
That seems to be related to a CORS issue... please check that CORS is enabled in your backend code.
我应该使用哪种方式?
http.get()
返回一个 Observable,所以使用它的一种方法是
http.get()
returns an Observable, so one way to use it would be
getResults(){
this.http.get('http://localhost/api.php')
.map(res => res.json());
}
然后当你调用那个方法时,你需要这样做:
And then when you call that method, you need to do it like this:
this.yourService.getResults().subscribe((data) => { console.log(data); });
如果你需要返回一个承诺,那么你可以这样做:
If you need to return a promise, then you can do it like this:
getResults(){
this.http.get('http://localhost/api.php')
.map(res => res.json())
.toPromise();
}
并像这样使用它
this.yourService.getResults().then((data) => { console.log(data); });
这篇关于离子 2 http.get() 问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文