【问题标题】:Rxjs BehaviorSubject error handling when used with mergemap与 mergemap 一起使用时的 Rxjs BehaviorSubject 错误处理
【发布时间】:2021-02-23 09:45:49
【问题描述】:

我有以下代码

@Injectable()
export class ReceptionService {
 private generalInfoDataSrc$ = new BehaviorSubject<any>(null);
 public generalInfoData = this.generalInfoDataSrc$.asObservable();
 
 setGeneralInfo(dataSrc: GeneralInfoMModal) {
    this.generalInfoDataSrc$.next(dataSrc);
 }
}

从我的component1我将上面设置为

OnSelect(patient: any) {    
let generalInfo = new GeneralInfoMModal();    
generalInfo.id = patient.id;
// some other code here
// this.recepService.setGeneralInfo(generalInfo);
}

 // from component2
 // 
 ngOnInit() { getPatientDetails() }
 getPatientDetails() {
  this.receptionService.generalInfoData.pipe(mergeMap(response => {
  if (response && response.id) {
    this.loading = true;
    return this.receptionService.get('User/Get' + response.id, this.sourceobj);
  } else {
    return of(null);
  }
}), takeUntil(this.unsubscribe$)).subscribe(response => {
  this.patient = response;
  this.loading = false;
}, error => {
  this.loading = false;
  // this.utility.showMsg('An error occurred while getting user.')
}, () => {

})
}

每件事都运作良好。我继续选择用户,从而调用 User/Get api。但是,如果 api 返回错误,则执行错误部分,之后当行为主体(选择用户)发生变化时,它不会调用用户/获取。是否有其他方法来处理 behaviorsubject 的错误或任何其他方法来处理这个想法。在这种情况下应该如何使用行为主体。

【问题讨论】:

    标签: angular7 rxjs6 behaviorsubject


    【解决方案1】:

    如果重复使用同一个行为主体,如果出现错误,需要将行为主体设置回null,这样下一个用户设置时,会得到最新的值。

    试试这样的:

    getPatientDetails() {
      this.receptionService.generalInfoData.pipe(mergeMap(response => {
      if (response && response.id) {
        this.loading = true;
        return this.receptionService.get('User/Get' + response.id, this.sourceobj);
      } else {
        return of(null);
      }
    }), takeUntil(this.unsubscribe$)).subscribe(response => {
      this.patient = response;
      this.loading = false;
    }, error => {
      this.loading = false;
      ///////////////////////////////// ADD THIS LINE ///////////////////////
      this.recepService.setGeneralInfo(null);
      // this.utility.showMsg('An error occurred while getting user.')
    }, () => {
    
    })
    

    【讨论】:

      猜你喜欢
      • 2019-09-07
      • 2019-12-29
      • 2021-04-19
      • 1970-01-01
      • 2022-01-24
      • 2020-05-14
      • 1970-01-01
      • 2023-04-02
      • 1970-01-01
      相关资源
      最近更新 更多