dimanche 19 juillet 2020

local state and global state in angular

Is it redundant to keep a local state in a component and an app state in a global service?

My goal is to centralized the data in one place (a store), but I also want my component to be stand alone as much as possible and to handle business logic sperific to that data

Let say I want my app to show some products.

I have a getProductsFromServer function in a products folder. A Guard/Resolver call that function each time the internal state inside the service changes, data is emited via a BehaviorSubject. I have one place in my app which is listening to that data so other components (if needed) can be notified from that centralized place.

// 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
})
}

Aucun commentaire:

Enregistrer un commentaire