Search code examples
angularrxjsangular7ngoninit

Subject not triggering when being called from parent component in ngOnInit


I'm using Rxjs and Angular 7. I have a parent component and a child component. I have a method to invoke a Subject on my child component:

updateSubject(text: string) {
  this.subject$.next(text);
}

And I'm calling this from my parent component in ngOnInit using ViewChild:

ngOnInit() {
  this.childComponent.updateSubject('New Text');
}

But the subscribe for this.subject$ is never triggered if I am calling it from ngOnInit in the parent component. If I call the method using a button from either parent or child, the the subscribe triggers fine. What am I doing wrong?

See the StackBlitz demonstration here.


Solution

  • The subscribe() in the child is being called after the parent is initialized. Angular initializes components in the same order as the DOM so the parent component is initialized first, and then the child is initialized.

    A Subject() throws away emitted values if nothing is subscribed, and since the child is subscribing late it doesn't receive the value.

    You can use a BehaviorSubject() or a ReplaySubject() depending if you need an initial value or not.