代码之家  ›  专栏  ›  技术社区  ›  micronyks

mobx&mobx angular:如何从存储更新和订阅更新的值?

  •  1
  • micronyks  · 技术社区  · 7 年前

    mobx mobx-angular (您可以在dependency中看到)。我来自ngrx,ngxs的背景,所以很难理解mobx流,因为它或多或少 angular-service

    DEMO APP

    存储.ts

    @Injectable()
    export class Store {
    
        @observable counter: number = 0;
    
        constructor() { }
    
        @action count() {
            this.counter ++;
        }
    }
    

    应用组件.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;
      }
    }
    

    应用程序组件.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>
    
    1 回复  |  直到 7 年前
        1
  •  2
  •   Richard Matsen    7 年前

    您可以在中设置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)
    
    推荐文章