【问题标题】:How to properly get the value of Mobx @observable in TypeScript?如何在 TypeScript 中正确获取 Mobx @observable 的值?
【发布时间】:2018-12-19 11:53:06
【问题描述】:

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

@observable customObject: customObject[] = [];

如果我想获得这个 observable 的值,我会在同一个类中创建一个方法吗:

选项 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?

【问题讨论】:

    标签: angular typescript rxjs store mobx


    【解决方案1】:

    您可以使用 mobx-utils 来处理 mobx FAQs 中提到的 RxJs。

    所以,假设你有 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

    【讨论】:

      【解决方案2】:

      您可以尝试像这样使用Observable.of();

      import { Observable } from 'rxjs';
      
      getCustomObject(): Observable<CustomObject[]> {
           return Observable.of(this.customObject);
      }
      

      【讨论】:

        【解决方案3】:

        根据 Ang4 或 6 使用

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

        并从 rxjs 导入 o​​bservable

        【讨论】:

          猜你喜欢
          • 2019-02-17
          • 1970-01-01
          • 1970-01-01
          • 2021-10-19
          • 2017-03-08
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-04-26
          相关资源
          最近更新 更多