Angular: 如何检测当前组件的路由变化?
Angular: How to detect route changes in current component?
我想检测当前组件的路由并尝试了类似的方法。但它会在每条路线开始和结束时触发。取而代之的是,当来自此 DetailsComponent
?
的路由发生变化时,我如何检测 only 路由变化
export class DetailsComponent {
constructor(private router: Router) {
this.router.events.subscribe((event: Event) => {
if (event instanceof NavigationStart) {
}
if (event instanceof NavigationEnd) {
}
});
}
}
我需要在从这个 DetailsComponent
导航时获取 url 并在 url 不是 /employees
时进行操作。
继续检测到您的事件的原因是,当您的 DetailsComponent
被销毁时,您没有取消订阅 router.events
。
如果您只是退订,它应该适合您:
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();
}
}
这是一个 StackBlitz 示例。
我想检测当前组件的路由并尝试了类似的方法。但它会在每条路线开始和结束时触发。取而代之的是,当来自此 DetailsComponent
?
export class DetailsComponent {
constructor(private router: Router) {
this.router.events.subscribe((event: Event) => {
if (event instanceof NavigationStart) {
}
if (event instanceof NavigationEnd) {
}
});
}
}
我需要在从这个 DetailsComponent
导航时获取 url 并在 url 不是 /employees
时进行操作。
继续检测到您的事件的原因是,当您的 DetailsComponent
被销毁时,您没有取消订阅 router.events
。
如果您只是退订,它应该适合您:
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();
}
}
这是一个 StackBlitz 示例。