我有棱角应用程序v6,我使用的是mobx和mobx-angular的最新版本(您可以在依赖项中看到)。我来自ngrx,ngxs背景,所以很难理解mobx流,因为它或多或少地带有额外的angular-service方法(还有性能)。
在stackblitz的例子中,我几乎没有问题。我希望有人能给他们指点。
store.ts
@Injectable()
export class Store {
@observable counter: number = 0;
constructor() { }
@action count() {
this.counter ++;
}
}app.component.ts
export class AppComponent {
_counter:number=0;
constructor(private store:Store){}
ngOnInit(){
// how to subscribe to updated value of counter from service and assign it to this._counter ????
this._counter = this.store.counter;
}
}app.component.html
<div *mobxAutorun>Counter : {{store.counter}}<br /></div>
______________________________________________
<div>Counter : {{store.counter}}<br /></div>
______________________________________________
<div>how to subscribe to updated value form 'counter' variable to '_counter' local variable????</div><br />
<div> {{_counter}} </div>
<button (click)="store.count()">Count</button>发布于 2018-09-22 22:28:10
您可以在ngOnInit中设置RxJ订阅。
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 };只需更改toRx的第一个参数
this.store.toRx(this.store.counterWrapper, 'counter')
.subscribe(val => this._counter = val)https://stackoverflow.com/questions/52437928
复制相似问题