在我的组件中,我订阅了一个像这样的变量:

import { Subject, of } from 'rxjs'

....
distance: number
constructor() {
    this.distance = 0;
    this.getDistance().subscribe(
      (newDistanceValue) => {
        console.log('newDistanceValue', newDistanceValue)
      }
    )
    ....
}

getDistance(): Observable<number> {
   return of(this.distance);
}


对于变量的初始值,我得到以下输出。

newDistanceValue 0


...但是当我用组件的其他方法更改值时,订户不会输出新的距离值。

我想念什么?

最佳答案

这是rxjs而不是rsjx :)

您每次调用getDistance时都会生成一个新的Observable,并且它仅发出一个值,该值是distance的当前值,而应将其设置为BehaviorSubject

import { BehaviorSubject } from 'rxjs'

....
distance$ = new BehaviorSubject(0)
constructor() {
    this.distance$.subscribe(
      (newDistanceValue) => {
        console.log('newDistanceValue', newDistanceValue)
      }
    )
    // or get value of distance synchronously
    console.log(this.distance$.getValue())
    ....
}

foo() {
    this.distance$.next(1)
}

07-26 01:02