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

标签 angular mobx angular-state-managmement

我有 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)

关于angular - mobx & mobx- Angular : how to update & subscribe to updated value from store?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52437928/

相关文章:

angular - 是否可以将 [routerLink] 绑定(bind)到 div? Angular 2+

angular - 将angular2中管道的输出分配给变量

Angular2 组件无法通过服务中的 observable 进行通信

javascript - 未知选项 : package. json.presets

Angular2 如何在组件代码中订阅事件?

reactjs - mobx - 领先的装饰器必须附加到类声明中

reactjs - 开 Jest : Unexpected token @ Decorator

state-management - 如何在 NGXS 中使用 patchState 与 setState?

javascript - 当状态发生变化而不发生突变时,Angular 会重新渲染组件列表

angular - NGXS 全局状态的切片在每次导航时发出