刷新时未获取“路由器事件”

问题描述 投票:0回答:4

我正在为我的项目做面包屑。我这里有两个问题:

  1. 当我来自其同级页面时,未生成面包屑
  2. 页面刷新时未生成面包屑

如何解决这两个问题?

import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute, RoutesRecognized, NavigationStart,  NavigationEnd, Params, PRIMARY_OUTLET } from '@angular/router';
import { filter, map } from 'rxjs/operators';
import { BreadCrumbsService } from './../../services/bread-crumbs.service';


@Component({
    selector: 'bread-crumbs',
    templateUrl: './bread-crumbs.component.html',
    styleUrls: ['./bread-crumbs.component.scss']
})
export class BreadCrumbsComponent implements OnInit {

    breadcrumbList: Array<any> = [];

    /**
        * Setting Breadcrumb object, where name for display, path for url match,
        link for heref value, getting datas from BreadCrumbsService service
    */

    constructor(private router: Router, private bCService: BreadCrumbsService) {

        this.generateBreadCrumb();

    }

    ngOnInit() {}

    generateBreadCrumb() {

        console.log('hi');

        let routerUrl: string, routerList: Array<any>, target: any;

        this.router.events.subscribe((router: any) => {

            console.log('do'); //not consoles on above 2 points

            routerUrl = router.urlAfterRedirects;


        });

    }

}
angular angular-router angular8
4个回答
2
投票

上述解决方案对我不起作用。我想出了以下解决方案

export BreadcrumbComponent implements OnInit {
        
isRefreshed = true; // dummy variable flag
   
     constructor(private router: Router, private activatedRoute: ActivatedRoute, public breadcrumbService: FinlexBreadcrumbService) {
       this.router.events
         .pipe(
           filter((event) => event instanceof NavigationEnd),
           distinctUntilChanged()
         )
         .subscribe(() => {
           //Build your breadcrumb starting with the root route of your current activated route. will call only on navigation change
           this.isRefreshed = false;
           this.breadcrumbService.buildBreadCrumb(this.activatedRoute.firstChild);
         });
     }
   
     ngOnInit(): void {
       if (this.isRefreshed) {
//will call only when page reload happens          
this.breadcrumbService.buildBreadCrumb(this.activatedRoute.firstChild);
       }
     }
}

1
投票

我正在使用的路由器订阅逻辑更具限制性并且有效:

constructor(private router: Router) { 
     router.events.subscribe(event => {
            if (event instanceof NavigationEnd) {
                console.log(event.urlAfterRedirects);
            }
          });
}

所以我认为您的问题是由您设置路由器模块的方式引起的。 您是否通过在两个 URL 中使用两个组件来测试路由器是否正常工作? 或者您愿意与我们分享您的路由器模块吗?


1
投票

我在条件中添加了另一种类型的事件,它解决了我的问题:

constructor(private router: Router) { 
   router.events
        .pipe(filter((event: any) => event instanceof NavigationEnd || event instanceof Scroll))
        .subscribe((val: any) => {
          console.log(val.url || val.routerEvent.url);
        })
}

0
投票

可能是因为您的组件稍后渲染根组件,最好从根组件创建服务并初始化路由监视服务方法

© www.soinside.com 2019 - 2024. All rights reserved.