[英]Executing code after router.navigate in Angular2
我想知道在使用角度路由器导航到不同的“视图”后是否有办法执行某些操作。
this.router.navigate(["/search", "1", ""]);
// Everything after navigate does not not get executed.
this.sideFiltersService.discoverFilter(category);
this.router.navigate 返回一个 promise,所以你可以简单地使用:
this.router.navigate(["/search", "1", ""]).then(()=>{ // do whatever you need after navigation succeeds });
不完全确定上下文,但一个选项是使用ActivatedRoute
订阅 URL 中的更改
https://angular.io/docs/ts/latest/guide/router.html#!#activated-route
下面是一个例子:
...
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
});
}
如果 url 不是您所需要的,那么您可以在ActivatedRoute
中订阅许多其他可观察对象,这些可观察对象列在该链接中。
订阅可以在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
,取决于在路由传递的参数。
您还必须确保没有正在进行的订阅......我遇到了同样的问题,就我而言,有一个订阅改变了路线。 所以路线改了两次。 但实际上你可以使用 promises,没错
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.