Call function at the end of Router.navigate

Viewed 5625

I want to call a certain function after a user logs in. The user may log in from any page and on a successful log in, the user is redirected back to the previous page that they were browsing.

I'm using Router.navigate for redirecting to the page.

After looking for a while NavigationEnd seems like an option which would work, but it applies to all router events, not just a specific one.

My login.component.ts has something like this:

// ...
this.authenticationService.login(this.credentials)
  .pipe(first())
  .subscribe(
    data => {
      this.router.navigate([this.returnUrl]);
      // Need to call a function `doSomething()` here.
    },
    error => {
      // Implement error handling
    });
// ...

I know that it's not a promise but I'm looking for something like:

this.router.navigate([this.returnUrl])
  .then(this.doSomething()); // or .pipe()
4 Answers

You can navigate by using .navigateByUrl() which returns a promise.

this.router.navigateByUrl(this.returnUrl).then(this.doSomething());

How about this?

this.router.events.subscribe(event => {
    if (event instanceof NavigationEnd) {
        if(event.url === "your-route") {
            //do your thing
        }
    }
});

You probably want to look into using some sort of lifecycle events.. You could either do an OnDestroy in the component you are navigating from. Or a OnInit in the component you are navigating too.

I think the easiest thing is to just listen for the NavigationEnd event like you mention, but stop listening after it happens.

this.authenticationService.login(this.credentials)
  .pipe(first())
  .subscribe(
    data => {
      this.router.navigate([this.returnUrl]);
      this.router.events.pipe(
        first(evt => evt instanceof NavigationEnd)
      ).subscribe(() => {
        this.doSomething(); 
      });
    },
    error => {
      // Implement error handling
    });

I think this is the correct and safe thing to do because you know that:

  1. There will be a NavigationEnd event coming
  2. It will be the correct event to trigger your code
  3. After that happens, you can stop listening
Related