Reputation: 633
I'm implementing an Angular 2 service which gets JSON data from play framework server by http request.
http://localhost:9000/read returns JSON data like [{"id":1,"name":"name1"},{"id":2,"name":"name2"}]
.
And here's my Angular service code (from this 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);
}
}
But the request in browser looks like this:
GET XHR http://localhost:4200/localhost:9000/read [HTTP/1.1 404 Not Found 5ms]
So Angular creates relative URL, when absolute URL is needed. So could I...
1)Fix it in code.
2)Or make Angular 2 and Play run on same port.
3)Use JSONP or something else.
Upvotes: 1
Views: 774
Reputation: 73337
The reason to your relative url is simply because you have a typo, which causes this. Instead of
private heroesUrl = "http:localhost:9000/read";
it should be
private heroesUrl = "http://localhost:9000/read";
No other magic should probably not be needed here. You might run into a cors issue. But since this is a playground, and not actual development, in case of CORS you can enable CORS easily in chrome. But this is naturally NOT recommended in a real-life app. But for playing, that would do just fine.
Upvotes: 4