2017-01-18 46 views
1

我正在實現一個Angular 2服務,它通過http請求從播放框架服務器獲取JSON數據。Angular 2 http請求播放REST服務器

http://localhost:9000/read返回JSON數據,如[{"id":1,"name":"name1"},{"id":2,"name":"name2"}]

這是我的角度服務代碼(從本教程https://angular.io/docs/ts/latest/guide/server-communication.html):

import { Injectable }  from '@angular/core'; 
import { Http, Response } from '@angular/http'; 
import { Hero }   from './hero'; 
import { Observable }  from 'rxjs/Observable'; 
@Injectable() 
export class HttpService { 
private heroesUrl = "http:localhost:9000/read"; // URL to web API 
constructor (private http: Http) {} 
getHeroes(): Observable<Hero[]> { 
return this.http.get(this.heroesUrl) 
       .map(this.extractData) 
       .catch(this.handleError); 
} 
private extractData(res: Response) { 
let body = res.json(); 
return body || { }; 
} 
private handleError (error: Response | any) { 
// In a real world app, we might use a remote logging infrastructure 
let errMsg: string; 
if (error instanceof Response) { 
    const body = error.json() || ''; 
    const err = body.error || JSON.stringify(body); 
    errMsg = `${error.status} - ${error.statusText || ''} ${err}`; 
} else { 
    errMsg = error.message ? error.message : error.toString(); 
} 
console.error(errMsg); 
return Observable.throw(errMsg); 
} 
} 

但在瀏覽器的請求是這樣的:

GET XHR http://localhost:4200/localhost:9000/read [HTTP/1.1 404 Not Found 5ms] 

所以角創建相對URL,當絕對URL是需要。 所以我可以...

1)修復它的代碼。

2)或者讓Angular 2和Play在相同的端口上運行。

3)使用JSONP或其他東西。

+2

它不應該是'http:// localhost:9000/read'嗎? – chrigu

回答

4

你的相對網址的原因僅僅是因爲你有一個錯字,這導致了這一點。取而代之的

private heroesUrl = "http:localhost:9000/read"; 

應該

private heroesUrl = "http://localhost:9000/read"; 

可能不應該在這裏不需要其他的法寶。您可能會遇到cors問題。但是由於這是一個遊樂場,而不是實際的開發,所以在CORS的情況下,您可以輕鬆地在Chrome中啓用CORS。但是這實際上不是在真實應用程序中推薦的。但是對於玩,這將會很好。

+0

謝謝,這工作。而你絕對正確的CORS問題的地方:) –

+0

是的,我是心理上的:D開玩笑 - 很好,它解決了! :) – Alex