【发布时间】:2017-04-01 15:05:17
【问题描述】:
对我的 api 的所有调用都是通过我使用“GET、POST、PUT、DELETE、PATCH”方法创建的服务进行的。如果这些调用中的任何一个失败,我想在警报中显示错误,并且如果错误状态为 401,则将用户重定向到登录。如何制作通用错误处理程序?
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));
}
}
【问题讨论】:
标签: javascript angular typescript error-handling ionic2