[英]Angular , @ViewChild does not update when the value of the child component changes in constructor/ngOninit
Below, I don't underestand why the console.log("My status:",status);下面,我不明白为什么 console.log("My status:",status); not showing while the child property had change,,, this is my child component
子属性发生变化时不显示,这是我的子组件
in the constructor i have this在构造函数中我有这个
@Output() public isLoged :Subject<boolean> = new Subject();
constructor(
private authService :AuthService,
) {
authService.getLoggedStatus.subscribe(status => this.isLoged.next(status) );
if(this.authService.isLoggedIn()){
console.log(" -----Logged---- ");
this.isLoged.next(true);
this.authService.getLoggedStatus.next(true);
}
}
and my parent component.ts和我的父 component.ts
logged :boolean ;
@ViewChild(LoginComponent) login:LoginComponent;
ngAfterViewInit() {
this.login.isLoged.subscribe(status => this.getChildProperty(status));
}
getChildProperty(status) {
this.logged = status;
console.log("My status :",status);
}
so the result in the console is just => ** -----Logged---- **所以控制台中的结果只是=> ** -----已记录---- **
but what i want is ** -----Logged----但我想要的是** -----已登录----
My status: true **我的状态:真**
Nb:the result shows just in case the code (in the childComp in consructor)is in a Onclock button!注意:结果显示以防万一代码(在 constructor 的 childComp 中)在 Onclock 按钮中!
Change the output to EventEmitter instead Subject.将 output 更改为 EventEmitter 而不是 Subject。
@Output() public isLoged = new EventEmitter ();
this.isLoged.emit(true);
And in the parent component template add the output decorator并在父组件模板中添加 output 装饰器
<child-component (isLoged)="onLoggedIn($event)"></child-component>
and finally create the function in the parent class最后在父 class 中创建 function
onLoggedIn(isloged) {
this.getChildProperty(isloged);
}
Thank you all for your reply, I solved my problem by adding the谢谢大家的回复,我通过添加解决了我的问题
BehaviorSubject
行为主体
instead of the Subject
.而不是
Subject
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.