【发布时间】:2022-08-19 19:02:28
【问题描述】:
我正在使用 Angular 中的一个类,并希望分享属于该类的一堆状态。所以我做了一堆BehaviorSubject
private subjects = {
a : new BehaviorSubject<A>(this.a),
b : new BehaviorSubject<B>(this.b),
c : new BehaviorSubject<C>(this.c),
d : new BehaviorSubject<D>(this.d),
e : new BehaviorSubject<E>(this.e),
}
为了防止泄漏主题的Observer 端并且只暴露Observable 端,我将主题设为私有并使用可观察对象公开:
observables = {
a : this.subjects.a.pipe(share()),
b : this.subjects.b.pipe(share()),
c : this.subjects.c.pipe(share()),
d : this.subjects.d.pipe(share()),
e : this.subjects.e.pipe(share()),
}
我认为 observables 应该能够从主题中生成,这样当我想添加更多主题时,我不需要手动修改 observables。就像是:
observables = (()=>{
let observables : {[Property in keyof typeof this.subjects]:Observable} = {}
for(let key in this.subjects)
{
observables[key] = this.subjects[key as keyof typeof this.subjects].pipe(share())
}
return observables;
})();
但是这里Observable 和share 不知道它们的泛型类型。我怎样才能使这项工作或是否有更好的模式?
标签: angular typescript rxjs observable