Reputation: 3055
Good day folks, I have this crazy idea to use service as cache store. so I have defined few variables in Service. The data is updated all right in service but changes not reflected on view. View gets already populated and service layer runs afterward. I am not sure, even if it is a good idea to store data in service? can some one shed light on it please. here is my service code:
categories : SelectItem[]=[];
constructor(private utilityService:UtilityService) {
}
//populate all drop downs array with initial data from db
populateAll() {
//get categories
this.getCategories();
//there are lot more calls here
}
private getCategories() {
if(this.categories.length==0){
this.utilityService.getAllCategories().subscribe(cat=>{
this.categories =
this.utilityService.getSelectItemPublished(cat,"Category");
})
}
}
This is how I call it in component
constructor(
private cache:CacheStoreService,
) { }
ngAfterViewInit()
{
this.categories=this.cache.categories;
this.depts=this.cache.depts;
this.focuses=this.cache.depts;
this.statuses=this.cache.statuses;
this.phases=this.cache.statuses;
this.visibilities=this.cache.visibilities;
}
ngOnInit() {
this.cache.populateAll();
Appreciate your help. One more question: How can I update the service varaibles, when new data is added in db-update the cache. **I know, i can return observable and subscribe to it in component. I am looking another way. Not sure, if it is do able? **
Thank you
Upvotes: 0
Views: 943
Reputation: 691645
Here is what happens:
this.cache.populateAll()
There are several ways to fix that.
The first way would be to avoid replacing the array by another one, but instead to fill the original array.
The second way would be to always request the array from the service, instead of storing a second reference in the component:
get categories() {
return this.cache.categories;
}
The third way would be to emit an event from an observable in the service, that the component would subscribe to to obtain the new categories.
Upvotes: 4