Angular RxJS嵌套订阅

Angular RxJS嵌套订阅,angular,rxjs,Angular,Rxjs,在下面的代码中是否可以避免嵌套订阅 this.requestService().subscribe( () => this.success(), error => { const errorDescription = { one: 5, two: 10 }; return this.error(errorDescription).subscribe(); }

在下面的代码中是否可以避免嵌套订阅

this.requestService().subscribe(
      () => this.success(),
      error => {
        const errorDescription = {
          one: 5,
          two: 10
        };
        return this.error(errorDescription).subscribe();
      }
    );
第二个
subscribe
是观测者错误回调的一部分。我们如何使用例如
switchMap
作为只有一个订阅?

似乎您需要一个,它将允许您用另一个流替换错误。尽管我们必须更新成功的结果处理:

this.requestService().pipe(
//处理成功价值
点击(()=>this.success()),
//当错误发生时
catchError(错误=>{
常量错误描述={
一:五,,
2:10
};
//我们切换到'this.error'流
返回此错误(errorDescription);
})
).subscribe(值=>{
//…在这里,您将同时收到:
//来自requestService()的事件
//以及由此产生的事件。错误(errorDescription)
});
这里有一篇文章详细概述了


希望这能有所帮助这里有一个避免“嵌套”订阅的方法。有了您提供的代码,这是我能想到的最好的了。如果你有任何问题,请告诉我,我会帮助你的

import { of, throwError } from 'rxjs'; 
import { map, switchMap, catchError } from 'rxjs/operators';


// this.requestService().subscribe(
//       () => this.success(),
//       error => {
//         const errorDescription = {
//           one: 5,
//           two: 10
//         };
//         return this.error(errorDescription).subscribe();
//       }
//     );

const error = throwError('oops');
const success = of('success!');
const handleError = (d) => of({one: 5, two: 10}).pipe(
  map(n => n),
  catchError(e => 'could not do 2nd network request')
);

const requestServiceSuccess = success.pipe(
  switchMap(d => of(d)),
  catchError(handleError)
)

const requestServiceFail = error.pipe(
  switchMap(d => of(d)),
  catchError(handleError)
)

// if your first network request succeeds, then you will see success
requestServiceSuccess.subscribe(
  (d) => console.log(d),
  (e) => console.log(e)
)
// if your first network request fails, then you will see your errorDescription
requestServiceFail.subscribe(
  (d) => console.log(d),
  (e) => console.log(e)
)
您可以将其粘贴到stackblitz中以检查日志


我可能会这样做:

this.requestService().pipe(catchError(e => {
  const errorDescription = {
      one: 5,
      two: 10
  };
  return this.error(errorDescription).pipe(switchMap(empty())); 
  // the switch to empty will prevent the error going to success
  // consider moving this into the error handler itself.
})).subscribe(
  () => this.success(),
  error => {
    //should never get here.
  }
);

catchError->switchMap->empty是一种在我的代码中经常出现的模式,因为我的错误处理程序应该更频繁地停止处理链。

您可以共享
this.error()
函数的代码吗?两个订阅可能会导致两个请求,在这里您需要小心。使用('success')的
您不会注意到,但请尝试添加('success')的
管道(点击(console.log))
。在您的代码中有一个甚至零订阅被认为是一种好的做法(零订阅可以通过使用
| async
管道插入角度或使用redux epics开箱即用来实现)。