mobx & mobx-angular :如何更新和订阅商店的更新值?

mobx & mobx-angular : how to update & subscribe to updated value from store?

我有 angular 应用程序 v6,我正在使用最新版本的 mobxmobx-angular(您可以在依赖项中看到)。我来自 ngrx、ngxs 背景,所以很难理解 mobx 流程,因为它或多或少 angular-service 方法有一些额外的东西(也有性能)。

我在 stackblitz 示例中问的问题很少。希望有人指点一下。

DEMO APP

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>

您可以在 ngOnInit 中设置 RxJs 订阅。

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)