【发布时间】:2020-01-26 08:31:13
【问题描述】:
我正在尝试在 Angular 中实现基于 Rxjs 的状态管理,但我一直坚持与组件共享状态。
这是我的实现:
private readonly _policies = new BehaviorSubject(<Policy[]>([]));
readonly policies$ = this._policies.asObservable();
get policies(): Policy[] {
return this._policies.getValue();
}
set policies(val: Policy[]) {
this._policies.next(val);
}
async fetchAll() {
this.policies = await this._policyService.index().toPromise();
}
async delete(policyId: string): Promise<any> {
try {
await this._policyService
.destroy(policyId)
.toPromise();
this.policies = this.policies.filter(policy => policy.id !== policyId);
} catch (e) {
}
}
在 shell 组件中,我只是将变量传递给子组件;
<policy-list
[policies]="_policyStoreService.policies$ | async"
(deletePolicyEmitter)="_policyStoreService.delete($event)">
FetchAll 在解析器中被调用;
resolve(route: ActivatedRouteSnapshot): any {
return this._leavePolicyStoreService.fetchAll();
}
我想在我的组件中将 _policyStoreService.policies$ 保留为共享的 observable。因此,当我添加/删除/更新策略时,会将更改推送给所有订阅者。在延迟加载模块中也可以使用该服务,并且只有在之前没有加载过的情况下才从 api 获取数据。
问题是我如何将此存储服务用作单例服务。我已经从延迟加载模块的提供程序中删除并将 @Injectable({providedIn: 'root'}) 插入其元数据。但仍然出现注入错误。
解决方案:我刚刚将 {providedIn: 'root'} 元数据添加到服务依赖项中。
【问题讨论】:
-
你为什么不尝试@ngrx?这正是您所需要的。
-
我之前尝试并使用过 ngRx,但它提供了很多样板代码。我想保持简单。
-
你只需要用同样多的代码创建一个reducer。而且您不需要做出任何架构决策:)
-
你有什么问题? “我被卡住了”不足以让我们为您提供帮助。如果您想知道这是否是一个好的模式,答案是肯定的 - 对于简单的应用程序,服务中的
Subject是处理状态的合理方式。 Here 是描述这种模式的文章。如果您在遇到特定问题时需要帮助,我建议您使用StackBlitz 来显示问题。 -
我已经更新了问题。