ViqMontana
ViqMontana

Reputation: 5698

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.

Upvotes: 1

Views: 2335

Answers (3)

khush
khush

Reputation: 2799

Use BehaviorSubject instead of Subject

subject$: BehaviorSubject<string> = new BehaviorSubject<string>(null);

Follow this question to understand difference between Subject and BehaviorSubject

Difference between Subject and BehaviorSubject

Upvotes: 0

Knelis
Knelis

Reputation: 7159

You need to use the AfterViewInit lifecycle hook. Your child component hasn't been rendered yet when OnInit is called.

So this will work:

ngAfterViewInit() {
 this.childComponent.updateSubject('View initialized');
}

Upvotes: 1

Reactgular
Reactgular

Reputation: 54821

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.

Upvotes: 4

Related Questions