[英]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. 我正在使用Rxjs和Angular7。我有一个父组件和一个子组件。 I have a method to invoke a
Subject
on my child component: 我有一种方法可以在子组件上调用
Subject
:
updateSubject(text: string) {
this.subject$.next(text);
}
And I'm calling this from my parent component in ngOnInit
using ViewChild
: 我使用
ViewChild
从ngOnInit
父组件中ngOnInit
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. 但是,如果我从父组件中的
ngOnInit
调用,则永远不会触发对this.subject$
的subscribe
。 If I call the method using a button from either parent or child, the the subscribe
triggers fine. 如果我使用父级或子级中的一个按钮调用该方法,则
subscribe
会触发。 What am I doing wrong? 我究竟做错了什么?
The subscribe()
in the child is being called after the parent is initialized. 父级初始化后 ,将调用子级中的
subscribe()
。 Angular initializes components in the same order as the DOM so the parent component is initialized first, and then the child is initialized. Angular按照与DOM相同的顺序初始化组件,因此先初始化父组件,然后再初始化子组件。
A Subject()
throws away emitted values if nothing is subscribed, and since the child is subscribing late it doesn't receive the value. 如果未订阅任何内容,则
Subject()
会丢弃发射的值,并且由于子级订阅较晚,因此不会接收该值。
You can use a BehaviorSubject() or a ReplaySubject() depending if you need an initial value or not. 您可以使用BehaviorSubject()或ReplaySubject()取决于您是否需要初始值。
You need to use the AfterViewInit
lifecycle hook. 您需要使用
AfterViewInit
生命周期挂钩。 Your child component hasn't been rendered yet when OnInit
is called. 调用
OnInit
时尚未渲染您的子组件。
So this will work: 所以这将工作:
ngAfterViewInit() {
this.childComponent.updateSubject('View initialized');
}
Use BehaviorSubject instead of Subject 使用BehaviorSubject代替Subject
subject$: BehaviorSubject<string> = new BehaviorSubject<string>(null);
Follow this question to understand difference between Subject and BehaviorSubject 遵循此问题以了解主题和行为主题之间的区别
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.