1

I have problem with refreshing access_token when it expires. Problem is few services at one time making requests to the server and I need solution to handle all of them,refresh token once and repeat them.

2 Answers2

3

You could implement a class that extends the Http one:

@Injectable()
export class CustomHttp extends Http {
    constructor(backend: ConnectionBackend, defaultOptions: RequestOptions) {
        super(backend, defaultOptions);
    }

    request(url: string | Request, options?: RequestOptionsArgs): Observable<Response> {

        console.log('request...');

        return super.request(url, options);        
    }

    get(url: string, options?: RequestOptionsArgs): Observable<Response> {

        console.log('get...');

        return super.get(url, options);
    }
}

And register it when bootstrapping your application:

bootstrap(AppComponent, [HTTP_PROVIDERS, ROUTER_PROVIDERS,
    provide(Http, {
        useFactory: (backend: XHRBackend, defaultOptions: RequestOptions) => new CustomHttp(backend, defaultOptions),
        deps: [XHRBackend, RequestOptions]
    })
]);

This way you will be able to intercept all requests in Angular2.

At this level you could check the token expiration date and execute the refresh token request. The flatMap operator will help you here to wait for the refresh token request to be executed to execute the trajet request.

See this code as a sample:

    request(url: string | Request, options?: RequestOptionsArgs): Observable<Response> {
   return me.authService
             .refreshAuthenticationObservable()
             //Use flatMap instead of map
             .flatMap((authenticationResult:AuthenticationResult) => {
                   if (authenticationResult.IsAuthenticated == true) {
                     // retry with new token
                     me.authService.setAuthorizationHeader(request.headers);
                     return super.request(url, request);
                   }
                   return Observable.throw(initialError);
    });
}

See this question for more details:

Community
  • 1
  • 1
Thierry Templier
  • 198,364
  • 44
  • 396
  • 360
  • Hey Thierry, the code ---- return me.authService---- where will this sit and why does this need a custom http implementation ? – shiv Mar 28 '16 at 13:21
  • Hey shiv. We need a custom http class to intercept transparently everything requests without updating existing code (http calls). You're right for "return me.authService...". I updated m'y answer. – Thierry Templier Mar 28 '16 at 13:31
0
Observable.forkJoin(
    this.http.get('/app/1').map((res:Response) => res.json()),
    this.http.get('/app/2').map((res:Response) => res.json())
).subscribe(
  data => {
    this.a = data[0]
    this.b = data[1]
    refreshToken();
  },
  err => console.error(err)
);
shiv
  • 383
  • 1
  • 4
  • 17