在 rxjs 中订阅一个变量

Subscribing a variable in rxjs

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

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)
}