3 回答

TA贡献1780条经验 获得超1个赞
当组件注册该事件时,已引发该事件。最好的解决方案是使用 rxjs 运算符,并让组件从注入的 Route 加载初始状态,如下所示:NavigationEndstartWith
const routerSub$ = this.router.events.pipe(
filter((e) => e instanceof NavigationEnd),
startWith(this.router)).
subscribe((event) => {
this.routes = event.url.toLowerCase().split('/');
this.currentRoute = this.routes[1];
if (this.currentRoute !== this.previousRoute) {
this.setBodyClassBasedOnRouter(this.routes);
this.previousRoute = this.currentRoute;
}
});
请注意,当构造函数运行时(如果在构造函数内部使用),仍不会呈现 HTML 元素。

TA贡献1834条经验 获得超8个赞
在构造函数中使用它
import { NavigationEnd, Router } from '@angular/router';
class ...
constructor(private router:Router) {
this.router.events
.pipe(
filter(event => event instanceof NavigationEnd),
map((event: NavigationEnd) => event.url))
.subscribe(url => {
const lastUrlSegment = url.split('?')[0].split('/').pop()
console.log(lastUrlSegment)
console.log(url)
});
}
添加回答
举报