Observable 最终无法从错误状态传入

Observable can't pass in finally from err state

不是第一次遇到这个问题。因为我想在网页上显示一些数据,所以即使http请求失败,我在err状态中也有一些逻辑。为了不重复 subscribeerr 中的代码,我习惯将它写在 complete/finally 状态中。

this.loadingResults = true;
this.service.get().subscribe(data => {
   // do something with the data
}, err => {
   this.initializeData();
}, () => {
   this.loadingResults = false;
   this.cd.detectChanges(); 
});

因为在页面中我使用微调器等待响应的时间,它何时到达(成功与否,在 subscribeerr),我想更改 loadingResults 值为 false 并使用 ChangeDetectorRef 刷新页面上的数据。

问题是上面的代码不能正常运行,我需要在finally函数处放弃:

this.loadingResults = true;
this.service.get().subscribe(data => {
   // do something with the data
   this.loadingResults = false;
   this.cd.detectChanges(); 
}, err => {
   this.initializeData();
   this.loadingResults = false; // duplicate
   this.cd.detectChanges(); // duplicate
});

使用 finally 并避免在其余响应类型中重复代码的最佳方法是什么?我看到它的行为不像来自后端的 try-catch-finally (Java/C#)

subscribe 回调 errorcomplete 是互斥的。如果另一个被触发,一个就不会被触发。相反,您可以使用 finalize 运算符。它会在完成或错误的情况下被触发。

this.loadingResults = true;
this.service.get().pipe(
  finalize(() => {
    this.loadingResults = false;
    this.cd.detectChanges(); 
  })
).subscribe(
  data => {
    // do something with the data
  }, 
  err => {
    this.initializeData();
  }
);

另外奇怪,你为什么要手动触发变化检测?是什么阻止它自动触发?