[英]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);
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 });
Not entirely sure of the context but an option would be to subscribe to a change in the URL using ActivatedRoute
不完全确定上下文,但一个选项是使用
ActivatedRoute
订阅 URL 中的更改
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 ActivatedRoute
which are listed in that link if url isn't quite what you need.如果 url 不是您所需要的,那么您可以在
ActivatedRoute
中订阅许多其他可观察对象,这些可观察对象列在该链接中。
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();
// 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
}
如果您是从导航ComponentA
到ComponentB
导航,你可以做任何行动之后再ngOnInit()
的函数ComponentB
,取决于在路由传递的参数。
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,没错
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.