首页 > 解决方案 > Angular 路由器事件 NavigationEnd 未按预期触发

问题描述

我在html中有一个带有* ngIf =“alertValue”的警报,在ts中我有一个带有'if'的函数,我希望当值变为“true”时我可以激活我的警报

我试过了

html

<div *ngIf="alertValue">
       <div class="alert alert-primary" role="alert">
          A simple primary alert—check it out!
       </div>
     </div>

TS

alertValue= false;
 this.router.events.subscribe(event => {
    if (event instanceof NavigationEnd) {
      this.showNotif(this.router.getCurrentNavigation().extras.state);
    }
 });

showNotif(data: any) {
  console.log(data);
  if (data !== undefined) {
    this.alertValue= true;
    console.warn(this.alertValue);
  }
}

"console.log (data);"我很好地恢复了我的价值“你好”,在"console.warn (this.alertValue);"我恢复了“真实”,这很好。

但是我的警报没有在 html 中激活。我试图放置一个按钮,允许将“true”传递给我的“alertValue”并且我的警报激活

所以我了解如何在功能期间激活我的警报

如果你有想法,我很感兴趣

标签: angular

解决方案


你得router.getCurrentNavigation().extras.state早点打电话。由于为时已晚,因此不会触发更改。

导航已经结束ngOnInit。试着把它放在构造函数中。

// earliest life cycle 
constructor() {
    this.router.events.subscribe(event => {
        if (event instanceof NavigationEnd) {
            // subscribing to NavigationEnd which is about to happen
        }
    });
}

ngOnInit(){
    this.router.events.subscribe(event => {
        if (event instanceof NavigationEnd) {
            // subscribing to NavigationEnd which already ended so it's waiting
        }
    });
}

如果您需要更多帮助,请告诉我,但还要解释更多关于您的代码的信息,我会关注这个问题。


推荐阅读