Hennadii Bolshakov
Hennadii Bolshakov

Reputation: 67

What is Angular analogue solution for AngularJS interceptors

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.

Upvotes: 1

Views: 237

Answers (2)

Thierry Templier
Thierry Templier

Reputation: 202256

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:

Upvotes: 3

shiv
shiv

Reputation: 393

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

Upvotes: 0

Related Questions