Angular中,第一次加载时this.router.events无法加载

14
有没有人知道如何在组件加载时第一次触发路由器事件?
我正在使用 Angular 8。
我有一个深链接,可以移动到另一个组件。所以当我点击深链接时,它会重定向到主页。这种情况发生在计算机启动新会话时。
因此,根据我的调查,当应用程序第一次加载时,(this.router.events)不返回任何内容。
请问有人能给我提供相关建议吗?
以下是我的代码:- app.component.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;
        }
      }
    });
  }

你能分享更多的代码吗? - Baruch Mashasha
2
希望这能帮到你:https://dev59.com/tlgQ5IYBdhLWcg3wJgiO - Lasal Sethiya
@LasalSethiya 好的,让我检查一下。 - Aakankshi Gupta
4个回答

23
当组件注册该事件时,NavigationEnd事件已经被触发。最好的解决办法是使用rxjs的startWith操作符,并让组件从注入的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;
        }
    });

请注意,当构造函数运行时(如果在构造函数内部使用),HTML 元素仍未呈现。

整洁,第一次使用startWith。 - Yehia A.Salam

4

在构造函数中使用它。

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)
        });
    
    }

0

首先加载与ActivatedRoute一起工作

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

0
你不需要使用router.event。你可以直接使用router.url来进行首次加载。
否则,你可以在首次加载时使用ActivatedRoute状态快照的URL,然后在后续的路由中使用router事件。
constructor(
  private route: ActivatedRoute,
  private router: Router,
){
  let activeRoute = this.route['_routerState']['snapshot'].url;
      
  this.routes = activeRoute.toLowerCase().split('/');
  this.currentRoute = this.routes[1];
  if (this.currentRoute !== this.previousRoute) {
    this.setBodyClassBasedOnRouter(this.routes);
    this.previousRoute = this.currentRoute;
  }

  this.router.events.subscribe({
    next: (rEvent: any) => {
      if(rEvent instanceof NavigationEnd) {
        this.routes = this.router.url.toLowerCase().split('/');
        this.currentRoute = this.routes[1];
        if (this.currentRoute !== this.previousRoute) {
          this.setBodyClassBasedOnRouter(this.routes);
          this.previousRoute = this.currentRoute;
        }
      }
    }
  )}      
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接