0

I have a class which extends angular Http class, let's call it MyHttp. I also have MyJwtHttp class which extends MyHttp class.

I want to be able to return the response as json the problem is that if I'm doing something like this:

myJwtHttp.request(..).map(res=>res.json()

and the implementation of the request method is:

class MyHttp extends Http {
    request(url,...){
        ..
         ..
    return super.request(url).subscribe(res=> doSomething(res))
    }
}

The problem here is that the map function is getting invoked before the subscriber of the MyHttp class. This causes the input of the doSomething(res) to be a json and not the response itself..

I have tried using last instead of map but it won't return the json to the caller of the request.

Any idea how to solve this issue?

Thierry Templier
  • 198,364
  • 44
  • 396
  • 360
tubu13
  • 924
  • 2
  • 17
  • 34
  • Are you sure you want to `subscribe` to your request, and call `doSomething(res)` instead of using `map` on it? – poke Mar 23 '16 at 21:49

1 Answers1

0

If you want to do something with the request within your MyHttp class, I would use the do operator instead of subscribing on the corresponding observable:

class MyHttp extends Http {
  request(url,...) {
    (...)
    return super.request(url).do(res=> doSomething(res));
  }
}

In your case, the request method doesn't return an observable but a subscription object corresponding to the call of the subscribe method.

From the rxjs documentation:

Invokes an action for each element in the observable sequence and invokes an action upon graceful or exceptional termination of the observable sequence.

This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline.

Regarding the execution order, I don't exactly know the implementation of the MyJwtHttp but if the map operator is used outside the MyHttp and MyJwtHttp classes, its associated callback should receive a response object and not the JSON content.

Community
  • 1
  • 1
Thierry Templier
  • 198,364
  • 44
  • 396
  • 360