为什么观察不到

Why observable is not observed

我有两个级别的可观察对象,代码如下所示:

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
}

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

您可以 return 来自 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'
      }
    })
  )
}