gpt4 book ai didi

error-handling - 向订阅RXJS发送错误

转载 作者:行者123 更新时间:2023-12-03 07:57:40 24 4
gpt4 key购买 nike

我创建了一个应该捕获错误的函数:

private pipeError(): any {
return catchError((error: HttpErrorResponse, caught: Observable<any>):
HttpErrorResponse | any => {
if (error.status === 400 || error.status === 402) {
return Observable.throw(error);
} else if (error.status === 401) {
this.router.navigate(['/login']);
return Observable.throw(error);
}
});
}

然后,我创建了一个函数,该函数应该向api发送查询:
private post(path: string, data: Object, headers: HttpHeaders = this.getHeaders()): Observable<Object> {
return this.http.post(`${this.apiUrl}${path}`, data, { headers }).pipe(
this.pipeError(),
map((response: Object): Object | any => {
if (response instanceof Object) {
return response;
} else {
return empty();
}
})
);
}

为了调用上面的函数,我创建了一个新函数,在其中传递了适当的参数:
userRegister(data: UserRegisterInterface): Observable<Object> {
return this.post('accounts/register/', data);
}

其他组件:
现在在另一个组件中,您订阅了此功能
this.createAccountSubscription = this.api.userRegister(datadata).subscribe((data) => {
console.log(data);
}, error => {
console.log(error);
});

我希望我的pipeError函数返回此错误订阅,但这不起作用,它可以:

enter image description here

最佳答案

您并不总是处理错误。我认为您可以这样重写pipeError():

import { throwError } from 'rxjs';

private pipeError(): any {
return catchError((error: HttpErrorResponse, caught: Observable<any>):
HttpErrorResponse | any => {
if (error.status === 401) {
this.router.navigate(['/login']);
}

return throwError(error);
});
}

关于error-handling - 向订阅RXJS发送错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52093810/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com