4

All my Backend API requests return new token information in headers, even when them throw exceptions. In the next request I need to send these new token information.

So I'm trying to figure out an unique and standard way to do that, so I'm trying:

let requestOptions = new RequestOptions(Object.assign({
      method: method,
      url: environment.apiHost + url,
      body: body,
      headers: authenticatedRequest ? this.requestService.getAuthHeaders() : this.requestService.getJsonHeaders(),
      withCredentials: authenticatedRequest
    }));

this.http.request(new Request(requestOptions))
        .map((res:Response) => { this.storageService.setAuthInfo(res.headers); res.json() } )
        .catch((error:any) => Observable.throw(error.json().error || 'Server error'));

The problem I'm facing with is that when I subscribe to this method, res variable is returning undefined.

What do you suggest me?

Pasp Ruby
  • 957
  • 1
  • 9
  • 22

1 Answers1

3

The problem is you have to return a response res.json() explicitly from your map function as you used {}.

this.http.request(new Request(requestOptions))
   .map((res:Response) => { 
       this.storageService.setAuthInfo(res.headers); 
       return res.json();
   } )
   .catch((error:any) => Observable.throw(error.json().error || 'Server error'));

Similar answer here

Community
  • 1
  • 1
Pankaj Parkar
  • 134,766
  • 23
  • 234
  • 299
  • It solved the related problem, but I'm facing a new one: When an error happens, it is not passing by map(), so it doesn't register new tokens. The solution would be set new token (`this.storageService.setAuthInfo(res.headers);`) on catch() also unless there is a request method which is called on success and error return. Any idea? – Pasp Ruby Nov 23 '16 at 16:17
  • @PaspRuby I'd say its worth opening new question, other people can also jump in with thoughts.. – Pankaj Parkar Nov 23 '16 at 16:19
  • Ok, here it is: http://stackoverflow.com/questions/40769737/angular-2-http-request-method-which-is-called-on-both-success-and-error-cases @Pankaj Parkar – Pasp Ruby Nov 23 '16 at 16:34