有没有办法处理从服务器发送的 403 响应,而无需在 catch 块中单独处理它们中的每一个?
searchCustomer(customerName: string): any {
if (customerName != "") {
let url = '{url}';
let headers = new Headers();
headers.append('accept', 'application/vnd.vetserve.customerlookup.v1.hal+json');
return this.http.fetch(url, { method: 'GET', headers: headers })
.then(response => response.json())
.catch(error => {
if(error.status==403){
this._messageService.showMessage('No permission', MessageService.type.error, error);
}
console.log(error);
}
);
}
}`
感谢@thebluefox建议插入,这是最好的方法,也是我需要的,api-client.ts 文件得到了类 ApiClient,我们可以像下面这样修改它.withInterceptor 中的 response(response( 条件捕获错误
export class ApiClient {
http:HttpClient = null;
constructor(aurelia:Aurelia, auth:AuthenticationService) {
let httpClient = new HttpClient();
httpClient.configure(httpConfig => {
httpConfig
.withDefaults({
headers: {
'Accept': 'application/json'
}
})
.withInterceptor({
request(request) {
if (!auth.isAuthenticated()) {
aurelia.setRoot('authentication');
};
request.headers.append('Authorization', 'bearer ' + auth.accessToken);
return request;
}
response(response) {
console.log(`Received ${response.status} ${response.url}`);
return response; // you can return a modified Response
}
})
.useStandardConfiguration()
.withBaseUrl(config.api_endpoint);
});
this.http = httpClient;
}
}