leo
leo

Reputation: 3055

Angular 2 - Variable defined in Service, not updating in view

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

Answers (1)

JB Nizet
JB Nizet

Reputation: 691645

Here is what happens:

  1. The service is initialized, and its categories is an empty array
  2. You tell the service to fetch data, by calling this.cache.populateAll()
  3. The service method sends an asynchronous request
  4. The component stores a reference to the service's categories array in its own categories. The array is still empty
  5. Long after, the response to the asynchronous request comes back. The callback is called. It doesn't populate the array referenced by the service and the component. Instead, it assigns a new array to the service's categories field. The component still references the old, empty array.

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

Related Questions