简体   繁体   中英

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 .

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.

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');
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM