Ionic 2 http.get()问题 [英] Ionic 2 http.get() issue
本文介绍了Ionic 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.
我应该使用哪种方式?
Which way should i use?
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); });
这篇关于Ionic 2 http.get()问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文