局部状态和全局状态成角度

时间:2020-07-19 20:38:10

标签: angular typescript design-patterns store

在组件中保持本地状态而在全局服务中保持应用程序状态是否多余?

我的目标是将数据集中在一个地方(一家商店),但是我也希望我的组件尽可能独立,并处理适合该数据的业务逻辑

假设我希望我的应用展示一些产品。

我在产品文件夹中具有 getProductsFromServer 功能。每当服务内部的状态发生更改时,就会执行功能的Guard / Resolver调用,并通过BehaviorSubject发出数据。我的应用程序中有一个地方正在监听这些数据,以便可以从该集中位置通知其他组件(如果需要)。

// app/resolvers/data.resolver.ts:

_poductService.fetchData();

// app/products/products.service

private _internalData: Products = {
isLoading: false,
isLoaded: false,
errors: null
data: []
};
public products$ = new BehaviorSubject(this._internalData);
fetchData(){
this.internalData = {...this.internalData,
isLoading: true
}
this.products$.next(this.internalData);
httpRequest.then(data => {
this.internalData = {...this.internalData,
isLoading: false,
isLoaded: true,
data
};
this.products$.next(this.internalData);
})

// app/store.service.ts

public state$ : BehaviorSubject;


this._poductService.products$.subscribe(data=>{
this.next({
...this.state$.getValue(),
products: data
})
}

0 个答案:

没有答案