Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

147
Views
Executing code after router.navigate in Angular2

I wonder if there is a way to execute something after i navigate to a different "view" using angular router.

this.router.navigate(["/search", "1", ""]);
// Everything after navigate does not not get executed.
this.sideFiltersService.discoverFilter(category);
about 4 years ago · Santiago Trujillo
3 answers
Answer question

0

this.router.navigate returns a promise so you can simply use:

this.router.navigate(["/search", "1", ""]).then(()=>{
  // do whatever you need after navigation succeeds
});

about 4 years ago · Santiago Trujillo Report

0

// In javascript
this.router.navigate(["/search", "1", ""])
    .then(succeeded => {
        if(succeeded)
        {
            // Do your stuff
        }
        else
        {
            // Do some other stuff
        }
    })
    .catch(error => {
        // Handle the error
    });

// In typescript you can use the javascript example as well.
// But you can also do:
try
{
    let succeeded = await this.router.navigate(["/search", "1", ""]);
    if(succeeded)
    {
        // Do your stuff
    }
    else
    {
        // Do some other stuff
    }
}
catch(error)
{
    // Handle the error
}
about 4 years ago · Santiago Trujillo Report

0

Not entirely sure of the context but an option would be to subscribe to a change in the URL using ActivatedRoute

https://angular.io/docs/ts/latest/guide/router.html#!#activated-route

Here's an example:

...
import { ActivatedRoute } from '@angular/router';
...

private _routerSubscription: any;

// Some class or service

constructor(private _route: ActivatedRoute){
    this._routerSubscription = this._route.url.subscribe(url => {
        // Your action/function will go here
    });
}

There are many other observables you can subscribe to in ActivatedRoute which are listed in that link if url isn't quite what you need.

The subscription can be done in the constructor() or in an ngOnInit() depending on what suits you best, just remember to clean up after yourself and unsubscribe in an ngOnDestroy() :)

this._routerSubscription.unsubscribe();
about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!