RxJS嵌套订阅

时间:2019-04-04 20:43:02

标签: angular rxjs

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

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

第二个subscribe是观察者错误回调的一部分。我们如何使用例如switchMap是否只有一个订阅?

3 个答案:

答案 0 :(得分:2)

好像您需要一个catchError,这将使您可以将错误替换为另一个流。尽管我们必须更新成功的结果处理:

this.requestService().pipe(

  // handle success value
  tap(() => this.success()),

  // when an error happens
  catchError(error => {
    const errorDescription = {
      one: 5,
      two: 10
    };

    // we switch to `this.error` stream
    return this.error(errorDescription);
  })
).subscribe(value=>{
  // ...here you'll receive both:
  // events from the requestService()
  // and events from this.error(errorDescription)
});

在此处详细介绍error handling in RxJS

的文章

希望这会有所帮助

答案 1 :(得分:0)

这里有一个避免“嵌套”订阅的想法。使用您提供的代码,这是我能提供的最好的代码。如果您有任何疑问,请告诉我,我们会帮助您。

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中以检查日志

https://stackblitz.com/fork/rxjs?devtoolsheight=60

答案 2 :(得分:0)

我可能会这样:

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->空是一种模式,在我的代码中经常出现,因为我的错误处理程序应该更频繁地停止处理链。

相关问题