[英]Angular: How to detect route changes in current component?
I want to detect a route from the current component and tried something like that.我想检测来自当前组件的路由并尝试了类似的方法。 But it is triggered on every route starts and ends.
但它会在每条路线的开始和结束时触发。 Instead of this, how can I detect only the route changes when routes from this
DetailsComponent
?取而代之的是,当来自此
DetailsComponent
的路由时,如何仅检测路由更改?
export class DetailsComponent {
constructor(private router: Router) {
this.router.events.subscribe((event: Event) => {
if (event instanceof NavigationStart) {
}
if (event instanceof NavigationEnd) {
}
});
}
}
I need to get the url while navigation from this DetailsComponent
and make an operation if the url is not /employees
.我需要在从该
DetailsComponent
导航时获取 url 并在 url 不是/employees
时进行操作。
The reason your events continue to be detected, is because you are not unsubscribing from router.events
when your DetailsComponent
is destroyed.继续检测到您的事件的原因是,当您的
DetailsComponent
被销毁时,您没有从router.events
退订。
If you simply unsubscribe, it should work for you:如果您只是取消订阅,它应该适合您:
export class DetailsComponent {
private sub = this.router.events
.pipe(
filter(event => event instanceof NavigationStart),
map(event => event as NavigationStart), // appease typescript
filter(event => event.url !== '/employees')
)
.subscribe(
event => console.log('[DetailsComponent] NOT going to "/employees"!', event)
);
constructor(private router: Router) { }
ngOnDestroy() {
console.log('>> STOP listening to events for DetailsComponent');
this.sub.unsubscribe();
}
}
Here's a StackBlitz example.这是一个StackBlitz示例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.