【问题标题】:Angular get the current routesAngular获取当前路线
【发布时间】:2019-06-06 03:34:35
【问题描述】:

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

  });

预期的面包屑路径是 => 设置/数据,点击设置时具有相应的路由

【问题讨论】:

  • 在构造函数中注入private router: Router,然后就可以使用this.router.url访问当前路由了

标签: angular routing breadcrumbs


【解决方案1】:

不带参数('?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]);
}

【讨论】:

  • 我只寻找设置/数据之类的路线。这一个 'console.log(window.location.href.split('?')[0]);'给出完整的网址。
  • 不需要使用香草。在 this.router 实例化的 Angular Route 已经拥有所有路由信息。
  • 如何把这个“settings/data?dataId=1100”和“settings/data”分开
  • @VitorPiovezam 谢谢 vitor。你完全正确!
【解决方案2】:

您好,您需要来自路由器的 ActivatedRoute 对象,并使用它来获取 url 并去除您想要的部分,而无需以下参数。

constructor(private route : ActivatedRoute) { }

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

【讨论】:

    【解决方案3】:

    您可以注入包含有关 url 段信息的ActivatedRoute。一个问题是它指向渲染组件的路由,而不是最近的路由。我猜您的面包屑将在某些根组件中呈现,以便它显示在页面上的任何位置。您可以做的是获取路线的孩子并以这种方式找到最新的路线。类似于while(route.firstChild) route=route.firstChild。您还需要触发面包屑的刷新。为此,您可以订阅路由器事件。

    【讨论】:

      【解决方案4】:

      你可以使用:

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

      【讨论】:

        猜你喜欢
        • 2017-07-21
        • 2018-04-07
        • 2020-03-11
        • 2023-03-24
        • 2014-02-25
        • 2015-12-04
        • 2014-09-10
        • 2015-09-14
        • 2015-10-08
        相关资源
        最近更新 更多