typescript 在 Angular2 中的 router.navigate 之后执行代码

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42808837/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 04:20:51  来源:igfitidea点击:

Executing code after router.navigate in Angular2

javascriptangulartypescript

提问by Dave Plug

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

回答by gabo bernal

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

this.router.navigate 返回一个 promise,所以你可以简单地使用:

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

回答by Borquaye

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

不完全确定上下文,但可以选择使用订阅 URL 中的更改 ActivatedRoute

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

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 ActivatedRoutewhich are listed in that link if url isn't quite what you need.

ActivatedRoute如果 url 不是您所需要的,您还可以订阅许多其他 observables,这些observables列在该链接中。

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

订阅可以在constructor()或 中完成,ngOnInit()具体取决于最适合您的方式,请记住自己清理并取消订阅ngOnDestroy():)

this._routerSubscription.unsubscribe();

回答by Ali Shahzad

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

如果您从 导航ComponentA到导航,ComponentB则您可以在 的ngOnInit()函数中执行任何操作ComponentB,具体取决于路由中传递的参数。

回答by Timothy

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

您还必须确保没有正在进行的订阅......我遇到了同样的问题,就我而言,有一个订阅改变了路线。所以路线改了两次。但实际上你可以使用 promises,没错