angular - 在 Angular 中使用 Rxjs 进行基本状态管理
问题描述
我正在尝试在 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'} 元数据添加到服务依赖项中。
解决方案
你可以在你的服务中使用一个简单的 RXJS 主题:
在您的服务中:
stateChanges: Subject<any> = new Subject<any>();
在您的组件中,您希望向可观察对象发出一个新事件:
this.yourService.stateChanges.next('Data to emit');
当你想监听新事件的组件中:
this.yourService.stateChanges.subscribe(data => console.log(data));
** 重要提示:不要忘记取消订阅 observable
推荐阅读
- c - 比较函数作为稍后使用的参数
- java - Java:当事件实际上丢失时,如何对收集事件消息的类设置时间限制
- php - 在 PHP,laravel 中更改索引数组
- react-native - 如何使用 React Native Navigation。像堆栈导航
- date - 年初至今在 DAX 中超过一年
- asp.net-core - 无法在 NGINX 代理后面的 Blazor 服务器上加载静态文件
- javascript - 控制台日志上的警告 sdk angularfire
- freemarker - Freemarker 迭代地图列表,例如:地图
> 带有类似菜单子页面的模式 - c# - 如何隐藏查找值
- wordpress - 哪个文件负责搜索wordpress