首页 > 解决方案 > 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);
    }

  } 

和我的父 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);
  }

所以控制台中的结果就是 => ** -----Logged---- **

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

我的状态:是的**

注意:结果显示以防万一代码(在构造函数中的 childComp 中)位于 Onclock 按钮中!

标签: angularsubscribeviewchild

解决方案


谢谢大家的回复,我通过添加解决了我的问题

行为主体

而不是Subject.


推荐阅读