问题描述
我有一个服务,它进行 http 调用以保存到数据库,有时会检索自定义异常。我的问题是如何通过行为主体恢复向表单报告的异常
我的服务:
data$ = new BehaviorSubject({
users: [],create: false
});
constructor( }
dispatch(action: Action): Observable<true | { error: string; }> {
switch (action.type) {
case ActionTypes.USER_CREATE:
this.createuser(action.payload);
return of(true);
default:
return of(true);
}
}
private createuser(user: User){
this.http.post({body : user}).pipe(
map((result) => result),catchError((err) => {
if (err.error?.title === 'Custom' && err.status === 400) {
////Get and return exception
return throwError(err);
} else {
return throwError(err);
}
})
)
.subscribe((response: any) => {
this.data$.next({...this.data$.value,create: true});
});
}
我的组合:
this.userService.dispatch({ type: ActionTypes.USER_CREATE payload: user });
this.userService.data$.subscribe((data) =>{
console.log(data);;
this.router.navigate(['/users/user/list']);
});
解决方法
你不能简单地做一些像设置你的行为主题形状这样的事情:
data$ = new BehaviorSubject({
users: [],error: null,create: false
});
并在您发现错误时设置 error
属性:
private createUser(user: User){
this.http.post({body : user}).pipe(
map((result) => result),catchError((err) => {
if (err.error?.title === 'Custom' && err.status === 400) {
////Get and return exception
this.data$.next({...this.data$.value,error: 'Your error message about the is statement'}); // Maybe err.message,whatever you want
return throwError(err);
} else {
// Same here with error message about your else statement
return throwError(err);
}
// And you should think about a default error message,err.message or whatever is returned
})
)
.subscribe((response: any) => {
if(response) {
this.data$.next({...this.data$.value,create: true});
}
});
}
因此您将能够处理组件中的错误字段:
this.userService.data$.subscribe((data) => {
if(!data.error) {
this.router.navigate(['/users/user/list']);
}
// You can also display a snackbar with the error message if you want. Adapt it with your need,maybe you only want a boolean
});