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