2016-11-01 113 views
2

我試圖用這兩種方法調用http.get()Ionic 2 http.get()問題

首先:示

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 
....... 

我應該使用哪種方法,可能是什麼問題?對於URL 0:

回答

3

響應與狀態,這似乎是相關的CORS問題空

...請檢查CORS在後端代碼啓用。

我應該使用哪種方式?

http.get()返回可觀察到的,所以,你需要做這樣一個方式來使用它會

getResults(){ 
    this.http.get('http://localhost/api.php') 
      .map(res => res.json()); 
} 

然後當你調用這個方法:

this.yourService.getResults().subscribe((data) => { console.log(data); }); 

如果你需要退回承諾,那麼你可以這樣做:

getResults(){ 
    this.http.get('http://localhost/api.php') 
      .map(res => res.json()) 
      .toPromise(); 
} 

並使用它這樣的

this.yourService.getResults().then((data) => { console.log(data); }); 
0

看起來這是一個CORS問題。通常你必須將允許訪問你的API的所有域列入白名單。但是,因爲你正在編寫一個離子應用程序,所以一旦你構建你的應用程序並在你的設備上運行它就無關緊要。這就是爲什麼我建議安裝一個允許你禁用CORS的瀏覽器插件。

你的兩個代碼片段都做同樣的事情。如果你不想使用可觀,我可能會用第一個選項去:

getResults() { 
    return this.http.get('http://localhost/api.php') 
        .toPromise(); 
} 

然後:

this.service.getResults().then(data => { 
    // Do something with data 
}); 
1

如果你在瀏覽器中測試,打CORS問題,離子有一個解決方案 你應該在ionic.config中放置類似的東西,當運行ionic服務時,這將代理沒有CORS的API。

{ 
    // ... 
    "proxies": [{ 
    "path": "/api", 
    "proxyUrl": "http://xxxxxxxxx" 
    }] 
} 

此處瞭解詳情:http://blog.ionic.io/handling-cors-issues-in-ionic/

+0

是。這解決了我的問題。 1投票了;) –