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

如何在typescript中正确获取mobx@observable的值?

  •  0
  • sander  · 技术社区  · 7 年前

    我有一个商店类,它有一个属性:

    @observable customObject: customObject[] = [];
    

    如果我想得到这个可观察的值,我会在同一个类中创建一个方法:

    方案1

    getCustomObject(): Observable<CustomObject[]> {
         return this.customObject;
    }
    // the observable I'm using would be imported from "rxjs" and not "mobx"
    

    选项2

    getCustomObject() {
         return this.customObject;
    }
    // How can I subscribe to this observable when the method doesn't return an observable?
    
    3 回复  |  直到 7 年前
        1
  •  0
  •   Jp Duminy    7 年前

    根据Ang4或6 使用

     getCustomObject(): Observable<CustomObject[]> {
         return this.customObject;
    }
    

    从RXJS导入可观察的

        2
  •  0
  •   Sergio Alen    7 年前

    你可以尝试使用 Observable.of(); 这样地:

    import { Observable } from 'rxjs';
    
    getCustomObject(): Observable<CustomObject[]> {
         return Observable.of(this.customObject);
    }
    
        3
  •  0
  •   Wand Maker    7 年前

    您可以使用mobx-utils-towork和rxjs,如中所述。 mobx FAQs .

    所以,假设您有store类,那么您可以添加一个返回rxjs的方法 Observable 如下图所示:

    import { observable } from 'mobx';
    import * as mobxUtils from 'mobx-utils';
    
    import { Observable, of, from } from 'rxjs';
    
    ...
    
    
    class Store {
        @observable customObject: any = [];
    
        rxjsObservable(): Observable<any[]> {
          return from(mobxUtils.toStream(() => this.customObject));
        }
    }
    

    要使用它,您可以订阅和使用值。示例如下:

      let store = new Store();
    
      store.rxjsObservable().subscribe((c) => {
        console.log("Received new value:", c);
      })
    
      store.customObject = [1,2,3];
      // Console will print 
      // => Received new value: [1, 2, 3]
    

    PS:示例使用RXJS 6。如果旧版本的RXJS,那么, from 可能必须替换为 Observable.from .

    推荐文章