簡體   English   中英

角獲取當前路線

[英]Angular get the current routes

我正在嘗試創建自定義面包屑。 我想獲取沒有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]);
}

您可以使用:

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

嗨,您將需要路由器中的ActivatedRoute對象,並使用它來獲取url並剝離您想要的部分,沒有參數,如下所示。

constructor(private route : ActivatedRoute) { }

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

您可以注入包含有關url段信息的ActivatedRoute 一個陷阱是它指向呈現組件的路線,而不是最新的路線。 我猜您的面包屑將在某個根組件中呈現,以便它顯示在頁面上的任何位置。 您可以做的是找到該路線的子級,然后以這種方式找到最新的路線。 類似while(route.firstChild) route=route.firstChild 您還需要觸發面包屑的刷新。 為此,您可以例如訂閱路由器事件。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM