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 => {

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'

1 Answers 11

up vote 1 down vote accepted

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


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();

Not the answer you're looking for? Browse other questions tagged or ask your own question.