您可以在中设置RxJs订阅
ngOnInit
ngOnInit() {
this.store.toRx(this.store, 'counter')
.subscribe(val => this._counter = val)
}
toRx
是一个方便的功能,可以添加到商店。
它使用Mobx
observe()
函数,每次指定项更改时只激活回调。
import { Injectable } from '@angular/core';
import { action, observable, observe } from 'mobx';
import { Observable } from 'rxjs';
@Injectable()
export class Store {
...
toRx(obj, prop) {
return Observable.create(observer =>
observe(obj, prop, (change) => observer.next(change.newValue), true)
);
}
}
如果您有要订阅的深度嵌套属性,例如
@Injectable()
export class Store {
...
@observable counterWrapper = { counter: 0 };
只需更改
梅花
this.store.toRx(this.store.counterWrapper, 'counter')
.subscribe(val => this._counter = val)