I want to consume a REST api which is running on another server in angular 2.
In the documentation they provide an example how to do it using observables:
import {Injectable} from 'angular2/core';
import {Http, Response} from 'angular2/http';
import {Hero} from './hero';
import {Observable} from 'rxjs/Observable';
@Injectable()
export class HeroService {
constructor (private http: Http) {}
private _heroesUrl = 'http://someserver:8080/heroes'; // URL to external web api
getHeroes () {
return this.http.get(this._heroesUrl)
.map(res => <Hero[]> res.json().data)
.catch(this.handleError);
}
private handleError (error: Response) {
// in a real world app, we may send the error to some remote logging infrastructure
// instead of just logging it to the console
console.error(error);
return Observable.throw(error.json().error || 'Server error');
}
}
Note that I just changed the _heroesUrl
in order to consume an external api, the rest is exactly as in the documentation.
Unfortunately it would throw me an error:
EXCEPTION: TypeError: this.http.get(...).map is not a function in [null]
Obviousely it won't get any data. How can I manipulate the http header so CORS requests can be handled?
Edit 1
- I fixed the CORS issue by setting the headers accordingly in my backend.
I added the imports for map & observables:
import 'rxjs/add/operator/map' import 'rxjs/Rx';
Now the former error disappeared, however, a new one popped up in my console:
Uncaught (in promise) TypeError: object is not a constructor(…) [undefined:1]
When I click on the exception to see it's origin in the chrome dev console, it would open a new empty tab... kind of stuck here now