我正在实现一个Angular 2服务,该服务通过http请求从播放框架服务器获取JSON数据。
http://localhost:9000/read返回[{"id":1,"name":"name1"},{"id":2,"name":"name2"}]
等JSON数据。
这是我的Angular服务代码(来自本教程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时,Angular会创建相对URL。 我也可以......
1)将其修复为代码。
2)或者让Angular 2和Play在同一个端口上运行。
3)使用JSONP或其他东西。
答案 0 :(得分:4)
你的相对网址的原因只是因为你有一个拼写错误,这导致了这一点。而不是
private heroesUrl = "http:localhost:9000/read";
应该是
private heroesUrl = "http://localhost:9000/read";
这里可能不需要其他魔法。你可能会遇到一个cors问题。但由于这是一个游乐场,而不是实际的开发,如果是CORS,你可以在chrome中轻松启用CORS。但这在现实应用中自然不推荐。但是对于比赛来说,这样做会很好。