在Angular中使用Rxjs进行基本状态管理

时间:2019-09-26 05:57:33

标签: 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$为共享状态。因此,当我添加/删除/更新策略时,将该更改推送给所有订阅者。也可以在延迟加载模块中使用该服务,并且仅在之前未加载时才从api获取数据。

问题是我如何将此存储服务用作单例服务。我已经从延迟加载模块的提供程序中删除,并将@Injectable({providedIn:'root'})插入其metada中。但是仍然出现注入错误。

解决方案:我刚刚将{providedIn:'root'}元数据添加到服务依赖项中。

1 个答案:

答案 0 :(得分:0)

您可以在服务中使用一个简单的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));
    

**重要提示:不要忘记退订可观察的