onInit函数抛出ExpressionChangedAfterItHaHasBeenCheckedError?

时间:2018-09-05 05:16:23

标签: angular

我正在学习 Angular 。我试图实现,在登录页面后重定向到首页。我尝试过之后,

app.component.html

<header *ngIf='loggedIn'>
<h1>Test portal</h1>
</header>
<login *ngIf='!loggedIn' (homeVar)="loadHome()">Loading..</login>

<router-outlet></router-outlet>

app.component.ts

export class AppComponent implements OnInit {
  loggedIn = 0;
  constructor(private router:Router){}
  ngOnInit(){
    if(!this.loggedIn){
      this.router.navigate(['']);
    }

  }
    loadHome():void{
      this.loggedIn=1;
      this.router.navigate(['home']);

  }

}

login.component.ts

export class loginComponent implements OnInit  {
    @Output() homeVar:EventEmitter<string> = new EventEmitter();

    @SessionStorage() session:any = "";

    ngOnInit(){
        if(this.session != ""){
            this.homeVar.emit(this.session);
        }
    }
   check(){
      this.session = "user";
   }
 }

上面的代码工作正常,但出现以下错误

  

错误错误:ExpressionChangedAfterItHasBeenCheckedError:表达   检查后已更改。先前的值:“ ngIf:0”。当前   值:“ ngIf:1”。

如何解决此问题?

3 个答案:

答案 0 :(得分:1)

login.component.ts 中尝试以下代码:-

ngOnInit(){
  if(this.session != null){

    // add setTimeout
    setTimeout(()=> {
      this.homeVar.emit(this.session);
    }, 0);

  }
}

答案 1 :(得分:1)

@mkHun为什么不尝试将变量loggedIn更改为boolean呢?

export class AppComponent implements OnInit {
  loggedIn :boolean = false;
  constructor(private router:Router){}
  ngOnInit(){
    if(!this.loggedIn){
      this.router.navigate(['']);
    }

  }
    loadHome():void{
      this.loggedIn = true;
      this.router.navigate(['home']);

  }

}

答案 2 :(得分:1)

不是在onInit内部使用构造函数发出事件

export class loginComponent {
    @Output() homeVar:EventEmitter<string> = new EventEmitter();

    @SessionStorage() session:any = "";

    constructor(){
        if(this.session != ""){
            this.homeVar.emit(this.session);
        }
    }
   check(){
      this.session = "user";
   }
 }

https://stackoverflow.com/a/48216423/2742156