Angular Handling Response Status And Adding Headers Globally
Posted By : Vishal Kumar | 23-Jan-2018
Hi Guys,
When you start developing an application then you need to handle response status 401 and 403. I think the best approach is that handle these response statuses globally. So I am going to tell you how to make injectable service for handling these responsibilities and also how to add headers with a request.
The accompanying code is a working usage of an Http benefit that sidetracks to Login course each time a REST API returns "Token_Expired". Note that it can be utilized as a substitution to the normal Http and all things considered, doesn't require to transform anything in your application's as of now existing components or services.
app.module.ts
providers: [
{provide: Http, useClass: ExtendedHttpService },
AuthService,
PartService,
AuthGuard
],
extended-HTTP.service.ts
import { Injectable, Injector } from '@angular/core';
import { Response, RequestOptions, RequestOptionsArgs } from '@angular/http';
import { Http, XHRBackend, Headers, Request } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import { Router } from '@angular/router';
import { AuthService } from './auth.service';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/throw';
@Injectable()
export class ExtendedHttpService extends Http {
private router;
private authService;
constructor(private injector: Injector, defaultOptions: RequestOptions, backend: XHRBackend) {
super(backend, defaultOptions);
}
request(url: string | Request, options?: RequestOptionsArgs): Observable<Response> {
if (typeof url === 'string') {
if (!options) {
options = { headers: new Headers() };
}
this.setHeaders(options);
} else {
this.setHeaders(url);
}
console.log("url: " + JSON.stringify(url) +", Options:" + options);
return super.request(url, options).catch(this.catchErrors());
}
private catchErrors() {
return (res: Response) => {
if (this.router == null) {
this.router = this.injector.get(Router);
}
if (res.status === 401 || res.status === 403) {
//handle authorization errors
//in this example I am navigating to login.
console.log("Error_Token_Expired: redirecting to login.");
this.router.navigate(['signin']);
}
return Observable.throw(res);
};
}
private setHeaders(objectToSetHeadersTo: Request | RequestOptionsArgs) {
if (this.authService == null) {
this.authService = this.injector.get(AuthService);
}
//add whatever header that you need to every request
//in this example I could set the header token by using authService that I've created
//objectToSetHeadersTo.headers.set('token', this.authService.getToken());
}
}
Conclusion: So you have done with this injectable service. Now you have to import this service and use for calling api.
Thanks,
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Vishal Kumar
Vishal Kumar is Master in Computers Application. He has good technical skills in Java and always motivated to learn new things.