我有一个服务,它调用http保存到数据库,有时检索自定义异常。我的问题是如何通过行为主题
恢复报告表单的异常My Service
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});
});
}
My comp:
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
});