微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Angular BehaviorSubject 和错误异常

如何解决Angular BehaviorSubject 和错误异常

我有一个服务,它进行 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
});

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。