首页 > 解决方案 > 在 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'} 元数据添加到服务依赖项中。

标签: angularrxjs

解决方案


你可以在你的服务中使用一个简单的 RXJS 主题:

  1. 在您的服务中:

    stateChanges: Subject<any> = new Subject<any>();
    
  2. 在您的组件中,您希望向可观察对象发出一个新事件:

    this.yourService.stateChanges.next('Data to emit');
    
  3. 当你想监听新事件的组件中:

    this.yourService.stateChanges.subscribe(data => console.log(data));
    

** 重要提示:不要忘记取消订阅 observable


推荐阅读