tubu13
tubu13

Reputation: 934

Angular 2: recover from http request, and redo the request

I have some basic flow I would like to implement using angular 2 and rxjs this is the flow:

Asumming the user is loged in, for each request:

  1. If request fail, catch the error,
  2. do something async (relogin in the background)
  3. if success re send the failed request
  4. if fails throw the error.

    class MyHttpWrapper {
     ctor(private http:Http) {}
    
     get (url, options) {
         //Do some pre request things with the options and url
    
         return this.get(url,options)
                         .map(res => res.json())
                         .catch((err, source) => {
                              // Here i want to reloging
                              someService.login().subscribe(res => 
                               //Here i want to re-execute the original request and return it to the caller of the myHttpwrapper.get() caller
                              ).catch(err => 
                                  //return error to the caller of the myHttpWrapper.get() 
                              )                               
                         }
     }
    

How can I do that?

Upvotes: 2

Views: 1271

Answers (1)

Thierry Templier
Thierry Templier

Reputation: 202176

I would try something like that:

return this.http.get(url,options)
           .catch((err, source) => {
             return someService.login()
                       .flatMap((res) => {
                         return this.http.get(url,options);
                       });
           })
           .map(res => res.json());

If there is an error on both login and the second get, the error will be thrown to the second callback of the subscribe method.

Upvotes: 4

Related Questions