Aak*_*pta 14 javascript typescript angular angular8
有谁知道如何在第一次加载组件时触发路由器事件?
我正在使用 Angular 8。
我有一个移动到另一个组件的深层链接。因此,当我单击深层链接时,它会重定向到主页。每当计算机启动新会话时就会发生这种情况。
因此,根据我的调查,当应用程序第一次加载时,它(this.router.events)什么也不返回。
任何人都可以向我提出有关它的建议吗?
以下是我的代码:- app.component.ts
ngAfterViewInit() {
this.getActivatedRoute();
}
Run Code Online (Sandbox Code Playgroud)
getActivatedRoute() {
debugger
const routerSub$ = this.router.events.subscribe((event) => {
if (event instanceof NavigationEnd) {
this.routes = event.url.toLowerCase().split('/');
this.currentRoute = this.routes[1];
if (this.currentRoute !== this.previousRoute) {
this.setBodyClassBasedOnRouter(this.routes);
this.previousRoute = this.currentRoute;
}
}
});
}
Run Code Online (Sandbox Code Playgroud)
Ela*_*iki 23
当组件注册该事件时,该NavigationEnd事件已被引发。最好的解决方案是使用 rxjsstartWith运算符,并让组件从注入的 Route 加载初始状态,如下所示:
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;
}
});
Run Code Online (Sandbox Code Playgroud)
请注意,当构造函数运行时(如果在构造函数内部使用),HTML 元素仍然不会呈现。
小智 0
...
constructor(public activatedroute: ActivatedRoute,) {}
...
this.activatedroute.url.subscribe(data=>{
....
})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8187 次 |
| 最近记录: |