Angular 获取当前路由

标签 angular routes breadcrumbs

我正在尝试创建自定义面包屑。我想在没有 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>

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

  });

预期的面包屑路径是 => 设置/数据以及点击设置时的相应路径

最佳答案

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

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

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

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

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

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

关于Angular 获取当前路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56470584/

相关文章:

c# - 路由未定义的 Controller

asp.net-mvc-3 - Asp.Net MVC 3 - 映射已经属于某个区域的单独路线

php - 搜索结果中的 WordPress 面包屑

eclipse - 如何在 Eclipse 中禁用面包屑导航

javascript - 我可以使用异步管道将变量放入 ngFor 中吗?

angular - 类型错误 : Cannot read property 'getPosts' of undefined

angular - Typescript 将 null 分配给类型不会触发错误

http - Angular2 - http调用代码覆盖率

reactjs - Nextjs 如何将多个路由映射到一个页面?

spring - 在没有 Web 流的情况下在 Spring 中管理路径面包屑的最佳实践