Reputation: 384
I created a generic build request method for all my api calls. The response comes in okay, but isn't passed outside of this method.
My api.ts class (snippet)
buildRequest(url, method, body?) {
let options = new RequestOptions({
url: this.apiUrl + url,
method: method,
body: body
});
let req = new Request(options);
return this.http.request(req)
.map(res => {
res.json();
})
.catch(this.handleError);
}
handleError(error: any) {
return Observable.throw(error.message);
}
In the same class I have defined all the calls like so:
getItem() {
return this.buildRequest('url', RequestMethod.Get)
}
Then from a component I do
this.api.getItem().subscribe(res => {
this.item = res;
}
})
Everywhere else, but inside the .map, the res is undefined. When I used regular
return this.http.get(...)
and the same logic displayed here, it worked fine. What am I doing wrong?
I am importing these two:
import {Observable} from 'rxjs/Observable';
import 'rxjs/Rx'
Upvotes: 0
Views: 146
Reputation: 23516
In your buildRequest
method you made a little mistake. When using lambda expressions with curly braces, you have to return something:
x => x.Field // <-- this is a shorthand
equals
x => { return x.Field; }
So your code in the .map
call should look like this:
return this.http.request(req)
.map(res => {
return res.json();
})
.catch(this.handleError);
Upvotes: 1