2
votes

I've been reading a lot of background on Angular/ReactJS and trying to get a good understanding of the lifecycle hooks and how it all plays together, but something that still confuses me is the following scenario.

Say you have a someService and in that service you define a BehaviorSubject called someBehaviorSubject. It is defined inside someService as:

public someBehaviorSubject= new BehaviorSubject<someInterface[]>([]);

That behavior subject is then subscribed to someAPIcall(argument: string): void. someService.someAPIcall is defined as:

someAPIcall(argument: string): void {
  this.http.get<someInterface[]>(argument).subscribe(this.someBehaviorSubject);
}

someInterface is defined as:

interface someInterface {
  data: string
}

Say there is a parent component called someParent and a child called someChild. someParent has two buttons which call:

someService.someAPIcall("A");

and

someService.someAPIcall("B");

respectively. someChild has the following in a template:

<div*ngFor="let data of someService.someBehaviorSubject | async">
  {{data}}
</div>

In my observations, when you click button A or button B in someParent, the data correctly renders either dataset A or B. However, if you click the other button after the first set of data has rendered it does not rerender the data with the new dataset. I expected that it would with the async pipe being directly subscribed to the BehaviorSubject. I don't understand why the data isn't redrawn?

1

1 Answers

3
votes

In order to update the BehaviorSubject value you need to use the next() function which will push the new value into the BehaviorSubject.

Example:

someAPIcall(argument: string): void {
  this.http.get<someInterface[]>(argument).subscribe(data => 
{
   this.someBehaviorSubject.next(data); 
});}

For more information about RxJS subjects, consider checking the documentation.