平面图中的rxjs条件 [英] rxjs condition inside flatmap

查看:95
本文介绍了平面图中的rxjs条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在flatMap中有一个条件来检查第一个可观察者返回的内容.如果不符合条件,我想中断并导航到其他页面.

I want to have a condition inside flatMap that checks what was returned by first observable. If condition is not met I would like to break and navigate to different page.

this.service.getData(id)
  .flatMap((data) => {
    if (!data) {
      return Observable.throw(new NoDataFoundError());
    }
    return Observable.forkJoin(
      this.service.getData2(id2),
      this.service.getData3(id3),
    );
  })
  .subscribe(
    ([data2, data3]) => {
      this.data2= data2;
      this.data3= data3;
    },
    (err) => {
      if (err instanceof NoDataFoundError) {
        this.router.navigate(...);
      }
    }
  );   

目前,我正在抛出特定的错误并捕获该错误,但是我不喜欢这种解决方案,因为它不是唯一可能引发错误并且if无法缩放的代码.

Currently I'm throwing specific error and catching it however I don't like this solution as it's not the only piece of code that could throw an error and the if is not scaling.

我考虑过filter或takeWhile运算符,但无法执行重定向.

I thought about filter or takeWhile operators but I won't be able to execute the redirect.

我还考虑过返回Observable.of而不是抛出它(在第4行中),但是然后我必须做if in subscription,它也会闻起来.

I also thought about returning Observable.of instead of throwing (in line 4) but then I would have to do the if in subscribe which also smells.

推荐答案

您可以在内执行 this.router.navigate return Observable.empty().flatMap .这样,您将只有一个 if 语句.

You can execute this.router.navigate and return Observable.empty() inside .flatMap. This way you will have a single if statement.

.flatMap(data => {
  if (!data) {
    this.router.navigate(...);
    return Observable.empty();
  }
  return (...);
})

但是通常可观察物应该是懒惰且纯净的(无副作用),这将使它们可预测且易于编写.副作用应仅由订户执行.

But usually Observables should be lazy and pure(free of side effects) this will make them predictable and easy to compose. Side effects should be performed only by subscriber.

在您的特定情况下,似乎合适的解决方案是将这种逻辑放在路由防护中,如此处所述- https://stackoverflow.com/a/39162538/3772379

In your specific case, it seems like the proper solution would be to put this logic in the route guard, like described here - https://stackoverflow.com/a/39162538/3772379

这篇关于平面图中的rxjs条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆