Angular,当子组件的值在构造器/ngOninit中发生变化时,@ViewChild不会更新 &



下面,我不明白为什么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);
}

所以控制台的结果就是=>** -----已登录---- **

但是我想要的是* *——记录——

我的状态:true* *

注:结果显示,只是在情况下,代码(在childComp在构造函数)是在一个Onclock按钮!

将输出改为EventEmitter

@Output() public isLoged = new EventEmitter ();
this.isLoged.emit(true);

在父组件模板中添加输出装饰器

<child-component (isLoged)="onLoggedIn($event)"></child-component>
最后在父类 中创建函数
onLoggedIn(isloged) {
this.getChildProperty(isloged);
}

感谢您的回复,我通过添加

解决了我的问题

BehaviorSubject

代替Subject.

最新更新