Thursday, 24 May 2018

Handling 401 Unauthorized using interceptor in Angular 4

In the catch, we can handle any and all errors that occur, of primary interest to this example is the 401 Unauthorized error   https://angular.io/api/common/http/HttpInterceptor.
Create a service 
Ex=> Service name is AuthorizationService

import { Injectable } from '@angular/core';
import { Request, XHRBackend, RequestOptions, Response,
Http, RequestOptionsArgs, Headers } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/throw';
import { AuthService } from './authentication.service';
import { UsersApi, LoopBackAuth } from '../sdk';
import { Router } from '@angular/router';
import { AppStateService } from './app-state.service';

@Injectable()
export class AuthorizationService extends Http {

constructor(backend: XHRBackend, defaultOptions: RequestOptions,
private router: Router, private auth: LoopBackAuth) {
super(backend, defaultOptions);
}

request(url:string | Request, options?:RequestOptionsArgs):Observable<Response> {
// do whatever like set custom request headers
return super.request(url, options).catch(this.catchErrors());
}

private catchErrors() {
return (res: Response) => {
if (res.status === 401) {
this.auth.clear();
localStorage.clear();
this.router.navigate(['/login']);
}
return Observable.throw(res);
};
}
}

Use this service in Application App module like this.

import { Http, XHRBackend, RequestOptions } from '@angular/http';
import { RouterModule, Router } from '@angular/router';
import { LoopBackAuth } from './../shared/sdk/services/core/auth.service';
import { AuthorizationService } from '../authorization.service';

providers: [
{
provide: Http,
useFactory: (backend: XHRBackend, options: RequestOptions,
router: Router, auth: LoopBackAuth) => {
return new AuthorizationService(backend, options, router, auth);
},
deps: [XHRBackend, RequestOptions, Router, LoopBackAuth]
}
]























No comments:

Post a Comment