Angular 获取当前路线

klm*_*han 2 routing breadcrumbs angular

我正在尝试创建自定义面包屑。我想在没有 dataid 的情况下获取当前路线。

我已经尝试了以下但它带有数据 ID 并且路由不起作用。

请专家指教。

实际链接: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>
Run Code Online (Sandbox Code Playgroud)

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

  });
Run Code Online (Sandbox Code Playgroud)

预期的面包屑路径是 => 设置/数据,点击设置时具有各自的路线

wen*_*jun 5

有很多方法可以在不带参数的情况下获取当前路由('?dataId=1100')。

这些是您可以使用 Vanilla JavaScript 实现的两种方式。

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

否则,您可以使用包中的AngularRouter模块@angular/router

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

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