Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular router event NavigationEnd not firing when expected

Tags:

angular

I have an alert in html with a * ngIf = "alertValue",and in ts I have a function with an 'if' and I wish I could activate my alert when the value goes to "true"

I tried

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);
  }
}

in the "console.log (data);" I recover well my value "hello", and in "console.warn (this.alertValue);" I recover "true" which is good.

But my alert is not activated in the html. I tried to put a button that allows to pass "true" to my "alertValue" and my alert activates

so I understand how to activate my alert during the function

If you have an idea, I'm interested

like image 961
Crine Avatar asked Jun 17 '19 15:06

Crine


1 Answers

You have to call router.getCurrentNavigation().extras.state earlier. Since it's too late it's not triggering changes.

The navigation has already ended in ngOnInit. Try putting it in the constructor instead.

// 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
        }
    });
}

Let me know if you need more help but also explain more about your code and I will watch this question.

like image 160
Ben Racicot Avatar answered Oct 26 '22 00:10

Ben Racicot