简体   繁体   中英

Angular get the current routes

I'm trying to create the custom breadcrumb. I would like to get the current routes without dataid.

I have tried the below but it is coming with data ID and routing is not working.

Expert advice please.

Actual link: http://localhost:4200/settings/data?dataId=1100

HTML

<ul >
  <li class="breadcrumb-item" *ngFor="let breadLink of breadcrumbListObj"><a [routerLink]="breadLink.link">{{breadLink.name}}</a></li>
</ul>

TS

 import { Component, OnInit } from '@angular/core';
    import { Location } from '@angular/common';
    import {Router, ActivatedRoute, NavigationEnd, RoutesRecognized, Params, PRIMARY_OUTLET} from '@angular/router'
    constructor(location: Location, activate: ActivatedRoute, router:Router) {

      router.events.subscribe((val) => {
      if (location.path() !== '') {
        this.route = location.path();
        this.breadcrumbListArray = this.route.split('/');
        for(let d of this.breadcrumbListArray) {
         this.breadcrumbListObj["link"] = "/" + d;
         this.breadcrumbListObj["name"] = d;
        }
      }

  });

Expected breadcrumb path is => settings/data with respective routes on click on settings

There are quite a few ways to get the current route without the parameters ('?dataId=1100').

These are the 2 ways you can do it with Vanilla JavaScript.

console.log(`${location.protocol}//${location.host}${location.pathname}`);
console.log(window.location.href.split('?')[0]);

Otherwise, you can use Angular's Router module from the @angular/router package.

import { Router } from '@angular/router';

constructor(private router: Router) {
  console.log(this.router.url.split('?')[0]);
}

You can use:

this.activate.queryParams.filter(params => params.dataId).subscribe(params => {
     console.log(params);
     this.dataId = params.dataId;
     console.log(this.dataId); 
});

Hi You would need the ActivatedRoute Object from the router and use it to get the url and strip the part you want sans the params as below.

constructor(private route : ActivatedRoute) { }

ngOnInit() {
 console.log(this.route.routeConfig.path.split('?')[0]);
}

You can inject the ActivatedRoute that contains information about the url segments. One gotcha is that it points to the route on which the component is rendered, not the most recent route. I'm guessing your breadcrumb will be rendered in some root component so that it displays anywhere on the page. What you can do is get the children of the route and find the most recent route this way. Something like while(route.firstChild) route=route.firstChild . You will need to trigger the refresh of your breadcrumb, too. To do that you can for example subscribe to the router events.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM