如何在 TypeScript 中正确获取 Mobx @observable 的值?
How to properly get the value of Mobx @observable in TypeScript?
我有一家商店 class,其中有 属性:
@observable customObject: customObject[] = [];
如果我想获得这个 observable 的值,我会在相同的 class 中创建一个方法吗:
选项 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?
根据 Ang4 或 6
使用
getCustomObject(): Observable<CustomObject[]> {
return this.customObject;
}
并从 rxjs 导入 observable
您可以像这样尝试使用 Observable.of();
:
import { Observable } from 'rxjs';
getCustomObject(): Observable<CustomObject[]> {
return Observable.of(this.customObject);
}
您可以使用 mobx-utils 来使用 mobx FAQs 中提到的 RxJs。
所以,假设你有商店 class,然后,你可以添加一个 returns 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
。
我有一家商店 class,其中有 属性:
@observable customObject: customObject[] = [];
如果我想获得这个 observable 的值,我会在相同的 class 中创建一个方法吗:
选项 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?
根据 Ang4 或 6 使用
getCustomObject(): Observable<CustomObject[]> {
return this.customObject;
}
并从 rxjs 导入 observable
您可以像这样尝试使用 Observable.of();
:
import { Observable } from 'rxjs';
getCustomObject(): Observable<CustomObject[]> {
return Observable.of(this.customObject);
}
您可以使用 mobx-utils 来使用 mobx FAQs 中提到的 RxJs。
所以,假设你有商店 class,然后,你可以添加一个 returns 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
。