Whenever a call is made to my API, it goes through a service I have created using methods such as "GET, POST, PUT, DELETE, PATCH". In case any of these calls fail, I want to display the error in an alert and if the error status is 401, redirect the user to the login page. How can I create a generic error handler for this?
api.service.ts
import { Injectable } from '@angular/core';
import { Http, RequestOptions, RequestOptionsArgs, Response, URLSearchParams } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import lodash from 'lodash';
@Injectable()
export class ApiService {
url: string = 'https://leetags-api.herokuapp.com';
options: RequestOptions = new RequestOptions({
withCredentials: true
});
constructor(private http: Http) {}
get(endpoint: string, params?: any, options: RequestOptionsArgs = {}): Observable<Response> {
if (params) {
const urlSearchParams: URLSearchParams = new URLSearchParams();
lodash.forEach(params, (value: any, key: string): void => urlSearchParams.set(key, value));
options.search = !options.search ? urlSearchParams : options.search;
}
return this.http.get(`${this.url}/${endpoint}`, this.options.merge(options));
}
post(endpoint: string, body: any, options?: RequestOptionsArgs): Observable<Response> {
return this.http.post(`${this.url}/${endpoint}`, body, this.options.merge(options));
}
put(endpoint: string, body: any, options?: RequestOptionsArgs): Observable<Response> {
return this.http.put(`${this.url}/${endpoint}`, body, this.options.merge(options));
}
delete(endpoint: string, options?: RequestOptionsArgs): Observable<Response> {
return this.http.delete(`${this.url}/${endpoint}`, this.options.merge(options));
}
patch(endpoint: string, body: any, options?: RequestOptionsArgs): Observable<Response> {
return this.http.put(`${this.url}/${endpoint}`, body, this.options.merge(options));
}
}