[Fixed] How can I listen for a Service variable change in a component in Angular

Issue

I have a component with a button that triggers showSummary() when clicked that calls a service Appraisal-summary.service.ts that has a method calc()

showSummary(appraisal) {
  this.summaryService.calc(appraisal);
}

with service Appraisal-summary.service.ts :

calc(appraisal) {
  ...
  //a 'scores' array is created (synchronously)
  return this.scores;
}

How do I listen for the synchronous result this.scores to trigger a function in an unrelated component summary.component.ts (that has already been initialised) that will use scores.

something like:
summary.component.ts:

ngOnInit(): void {
  service.subscribe(scores => this.data = scores)
}

Solution

You would want to add a Subject inside your Appraisal-summary.service.ts like this:

import { Subject } from 'rxjs';

...
export class AppraisalSummaryService {
    // I am guessing scores is an array of type number
    public scoreSubject = new Subject<number[]>(); 
    
    calc(appraisal) {
      ...
      //a 'scores' array is created (synchronously)
      
      this.scoreSubject.next(this.scores); //emit the scores result
      return this.scores;
   }
}

And, in your other component, inside your ngOnInit, you want to listen to this result:

import { Subscription } from 'rxjs';
....
export class YourOtherComponent implements OnInit, OnDestroy {
   private subscription: Subscription;

   constructor(private appraisalSummaryService: AppraisalSummaryService) {}

   public ngOnInit(): void {
     // you store your subscribe
     this.subscription = this.appraisalSummaryService.subscribe((scores: number[]) => {
       console.log(scores);
    });
   }
   
   public onDestroy(): void {
     // you need this in order to avoid a memory leak
     this.subscription.unsubscribe();
   }
   
}
```

Leave a Reply

(*) Required, Your email will not be published