【发布时间】:2018-03-04 14:28:30
【问题描述】:
我是 RxJS 的新手。我想创建一个可以随时更改的AppState 对象的可观察对象,并订阅它以获取这些更改。这是一个精简的实现:
export class AppState {
public get observable(): Observable<any> {
return Observable.of(this._state);
}
}
// appState is injected into my component via angular DI
this.appState.observable
.subscribe((appState) => {
console.log('appState: ', appState);)
}, (err) => {
console.log('Error: ' + err);
}, () =>{
console.log('Completed');
});
但它只运行一次并立即调用completed。所以当我改变我的 appState 时,订阅已经结束了。
如何让订阅永远有效,就像 KnockOutJS 风格一样。这在 Angular 应用程序中使用
更新:我部分使用了Subject。但问题是现在它发出了许多相同值的重复。
// full appState.ts
import { Injectable } from '@angular/core';
import { Observable, Subject, BehaviorSubject } from 'rxjs';
export type InternalStateType = {
[key: string]: any
};
@Injectable()
export class AppState {
public _state: InternalStateType = {};
public subject: Subject<any>;
constructor() {
this.subject = new Subject();
}
/**
* Return an observable for subscribing to.
*/
public get observable() {
return this.subject;
}
/**
* Return a clone of the current state.
*/
public get state() {
this._state = this._clone(this._state);
this.subject.next(this._state);
return this._state;
}
/**
* Never allow mutation
*/
public set state(value) {
throw new Error('do not mutate the `.state` directly');
}
public get(prop?: any) {
/**
* Use our state getter for the clone.
*/
const state = this.state;
return state.hasOwnProperty(prop) ? state[prop] : state;
}
public set(prop: string, value: any) {
/**
* Internally mutate our state.
*/
return this._state[prop] = value;
}
private _clone(object: InternalStateType) {
/**
* Simple object clone.
*/
return JSON.parse(JSON.stringify(object));
}
}
需要进行哪些更改才能使其对this._state 的每次更改仅发出一次更改?
【问题讨论】:
标签: angular rxjs observable store subscription