在我的组件中,我订阅了一个像这样的变量:
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
...但是当我用组件的其他方法更改值时,订户不会输出新的距离值。
我想念什么?
答案 0 :(得分:1)
它是rxjs而不是rsjx:)
每次调用getDistance
时都会生成一个新的Observable,并且它仅发出一个值,即distance
的当前值,而应将其设为BehaviorSubject
< / p>
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)
}