[英]Show error message on bad request with Angular HTTP
I have a part of code on my services that check for a bad request in HTTP requests and send an alert on the user. 我的服务中有一部分代码可以检查HTTP请求中的错误请求,并向用户发送警报。 Also, I have another message that raise if the request was succeed. 另外,如果请求成功,我还会收到另一条消息。 However, my problem is that in case of an error, both messages are raised. 但是,我的问题是在发生错误的情况下,两个消息都会引发。
This is my service: 这是我的服务:
deleteProduct(product:Product) {
if ( this._loggedInGuard.isLoggedIn() ) {
let token = localStorage.getItem('token');
let body = JSON.stringify(product);
let headers = new Headers(
{ 'Content-Type': 'application/json',
"X-HTTP-Method-Override": "DELETE",
'Authorization': 'Bearer ' + token});
return this._http
.post(this.API + "/products/"+product.id, body, {headers: headers} )
.map(res => res.json())
.catch(this._responseService.catchBadResponse)
.finally(() => this._responseService.success('Well done'));
}
}
And this is my ResponseService
code: 这是我的ResponseService
代码:
@Injectable()
export class ResponseService {
constructor() { }
catchBadResponse: (errorResponse: any) => Observable<any> = (errorResponse: any) => {
let res = <Response>errorResponse;
let err = res.json();
let emsg = err ?
(err.error ? err.error : JSON.stringify(err)) :
(res.statusText || 'unknown error');
Messenger().post( { message: emsg.message, hideAfter: 10, type: 'error', showCloseButton: false } );
return Observable.of();
}
success(msg) {
Messenger().post( { message: msg, hideAfter: 10, type: 'success', showCloseButton: false } );
}
}
I guess I need to add an exception on finally()
to be executed only if I don't have any error. 我想我只有在没有任何错误的情况下, finally()
需要在finally()
上添加一个例外才能执行。 But I am not able to make it work. 但是我无法使其工作。
Finally
is always called. Finally
总是被调用。 Replace your finally
with do
. finally
用do
代替。 The do is not executed when a exception is catched 捕获异常时不执行do
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.