预期时不会触发角路由器事件NavigationEnd

时间:2019-06-17 15:29:07

标签: angular

我在带有* ngIf =“ alertValue”的html中有一个警报,在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);"中,我很好地恢复了值“ hello”, 在"console.warn (this.alertValue);"中,我恢复了“ true”,这很好。

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

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

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

1 个答案:

答案 0 :(得分:0)

您必须提前致电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
        }
    });
}

让我知道您是否需要更多帮助,但也请解释一下您的代码,我将关注这个问题。

相关问题