如何解决Angular , @ViewChild 在构造函数/ngOninit 中子组件的值发生变化时不会更新
下面,我不明白为什么 console.log("My status :",status);子属性发生变化时不显示,这是我的子组件
在构造函数中我有这个
@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);
}
}
和我的父组件.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);
}
所以控制台中的结果就是 => ** -----已记录---- **
但我想要的是 ** -----已记录----
我的状态:真实 **
Nb :结果显示以防万一代码(在构造函数的 childComp 中)在 Onclock 按钮中!
解决方法
将输出更改为 EventEmitter 而不是 Subject。
@Output() public isLoged = new EventEmitter ();
this.isLoged.emit(true);
并在父组件模板中添加输出装饰器
<child-component (isLoged)="onLoggedIn($event)"></child-component>
最后在父类中创建函数
onLoggedIn(isloged) {
this.getChildProperty(isloged);
}
,
感谢大家的回复,我通过添加解决了我的问题
行为主体
而不是 Subject
。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。