![](/img/trans.png)
[英]ngOnInit() when called from another component does not refresh the component
[英]Subject not triggering when being called from parent component in ngOnInit
我正在使用Rxjs和Angular7。我有一個父組件和一個子組件。 我有一種方法可以在子組件上調用Subject
:
updateSubject(text: string) {
this.subject$.next(text);
}
我使用ViewChild
從ngOnInit
父組件中ngOnInit
ViewChild
:
ngOnInit() {
this.childComponent.updateSubject('New Text');
}
但是,如果我從父組件中的ngOnInit
調用,則永遠不會觸發對this.subject$
的subscribe
。 如果我使用父級或子級中的一個按鈕調用該方法,則subscribe
會觸發。 我究竟做錯了什么?
在此處查看StackBlitz演示。
父級初始化后 ,將調用子級中的subscribe()
。 Angular按照與DOM相同的順序初始化組件,因此先初始化父組件,然后再初始化子組件。
如果未訂閱任何內容,則Subject()
會丟棄發射的值,並且由於子級訂閱較晚,因此不會接收該值。
您可以使用BehaviorSubject()或ReplaySubject()取決於您是否需要初始值。
您需要使用AfterViewInit
生命周期掛鈎。 調用OnInit
時尚未渲染您的子組件。
所以這將工作:
ngAfterViewInit() {
this.childComponent.updateSubject('View initialized');
}
使用BehaviorSubject代替Subject
subject$: BehaviorSubject<string> = new BehaviorSubject<string>(null);
遵循此問題以了解主題和行為主題之間的區別
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.