Ich implementiere einen Angular 2-Dienst, der JSON-Daten vom Playframework-Server per HTTP-Anfrage erhält.Angular 2 HTTP-Anfrage an Play REST-Server
http://localhost:9000/read gibt JSON-Daten wie [{"id":1,"name":"name1"},{"id":2,"name":"name2"}]
zurück.
Und hier ist mein Eckige Service-Code (aus diesem Tutorial 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);
}
}
Aber die Anfrage in Browser wie folgt aussieht:
GET XHR http://localhost:4200/localhost:9000/read [HTTP/1.1 404 Not Found 5ms]
So Angular schafft relative URL, wenn absolute URL erforderlich. So könnte ich ...
1) Fix es in Code.
2) Oder machen Sie Angular 2 und Play auf demselben Port laufen.
3) Verwenden Sie JSONP oder etwas anderes.
Sollte es nicht "http: // localhost: 9000/read" sein? – chrigu