Executing code after router.navigate in Angular2

2020-02-28 03:49发布

问题:

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

回答1:

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

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



回答2:

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


回答3:

If you are navigated from ComponentA to ComponentB then after navigating you can do any actions in ngOnInit() function of ComponentB, depending upon the parameters passed in the route.



回答4:

You also have to ensure that there are no ongoing subscriptions... I faced the same problem and in my case there was a subscription which changed route. So the route has been changed twice. But practically you can use promises, thats right