首页 > 解决方案 > 为什么观察不到可观察的

问题描述

我有两个级别的 observables,代码如下所示:

function level_1() {
    ...
    level_2(params).subscribe((value) => {
        if (value === something) {
            action_1();
        }
        else { // others
            action_2();
        }
    });
}

function level_2(params) : Observable<any> {
    ...

    another_observable.subscribe((v) => {
        if (a_condition) {
            return of(something); // this is reached, but the observable is not captured
        }
        else {
            return of (others);
        }
    });

    return of(others); // this is captured
}

现在的问题是,在这三个“返回”中,level_1中只捕获了第三个,而level_2中达到了第一个,而level_1中没有捕获到第一个。我虽然 observable 会继续听,但我有什么遗漏吗?

标签: javascriptrxjsobservablesubscribe

解决方案


您可以从 中返回一个 observable level_2,然后可以在 中订阅它level_1

function level_1() {
  level_2().subscribe(value => {
    if (value === 'something') {
      console.log('action_1')
    }
    else {
      console.log('action_2')
    }
  })
}

const another_observable = of(true) // This is just to make this example work

function level_2() {
  return another_observable.pipe(
    switchMap(value => {
      if (value) {
        return of('something')
      }
      else {
        return of('others')
      }
    })
  )
}

level_1()

...或者如果您只需要切换到一个值而不是另一个可观察的值,您可以使用map而不是:switchMap

function level_2() {
  return another_observable.pipe(
    map(value => {
      if (value) {
        return 'something'
      }
      else {
        return 'others'
      }
    })
  )
}

推荐阅读