更新时间:2023-12-02 15:48:46
Steve 的答案是当前记录的答案,但是 ActivatedRoute
上的 url observable 没有为我触发,除非我第一次击中基地url(例如:从/index 到/index/item 有效,但从/index/item 到 index/item/2、index/dashboard,甚至/index 都不起作用).
Steve's answer is the one documented currently, but the url observable on ActivatedRoute
is not firing for me except when I first hit the base url (ex: going from /index to /index/item works, but going from /index/item to index/item/2, index/dashboard, or even /index does not).
我不确定以下解决方案是否是***实践,也不确定对性能的影响是什么,但我能够在路由器的 NavigationEnd
事件上获得活动路由,如下所示:
I'm not sure if the following solution is a best practice nor what the performance implications are, but I was able to get the active route on the NavigationEnd
event of the router with the following:
import { Component, OnInit, OnDestroy } from '@angular/core';
import { ROUTER_DIRECTIVES, Router, NavigationEnd } from '@angular/router';
@Component({
selector: 'navbar',
directives: [ROUTER_DIRECTIVES],
template: `
...
`
})
export class NavBarComponent implements OnInit, OnDestroy {
private sub: any;
constructor(private router: Router) {
}
ngOnInit() {
this.sub = this.router.events.subscribe(e => {
if (e instanceof NavigationEnd) {
console.log(e.url);
}
});
}
ngOnDestroy() {
this.sub.unsubscribe();
}
}
每次更改路线时都会触发,无论您在 url 树中有多深或导航到/从哪里.
This fires every time you change the route, regardless of how deep you are in the url tree or where you navigate to/from.