2017-01-18 48 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