为了账号安全,请及时绑定邮箱和手机立即绑定

此路由器事件在安格朗中首次加载时未加载

此路由器事件在安格朗中首次加载时未加载

白衣非少年 2022-09-29 15:23:01
有没有人知道如何在首次加载组件时触发路由器事件?我使用的是角度8。我有一个深层链接,可以移动到另一个组件。因此,当我单击深层链接时,它会重定向到主页。每当计算机启动新会话时,都会发生这种情况。因此,根据我的调查,当应用程序首次加载时,它(this.router.events)不返回任何内容。任何人都可以向我建议它。以下是我的代码:- 应用程序组件.ts ngAfterViewInit() {    this.getActivatedRoute();}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;        }      }    });  }
查看完整描述

3 回答

?
慕神8447489

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 元素。


查看完整回答
反对 回复 2022-09-29
?
MMMHUHU

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)

        });

    

    }


查看完整回答
反对 回复 2022-09-29
?
慕村225694

TA贡献1880条经验 获得超4个赞

使用激活布线的第一个负载

...constructor(public activatedroute: ActivatedRoute,) {}
... 
this.activatedroute.url.subscribe(data=>{
            ....
     })


查看完整回答
反对 回复 2022-09-29
  • 3 回答
  • 0 关注
  • 124 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号