在 Angular 2 中获取 url 没有参数的路径

Get url path without parameters in Angular2+

有没有办法获取 url 不带参数的路径。

如果我在 RouterModule 中有这个:

{ path: 'one/two', component: OneTwoComponent }
{ path: 'one/two/:id', component: OneTwoComponent }

我需要获取字符串

"/one/two"

我的 NavigationService 在这两种情况下,有和没有 id。

这样试试:

constructor(private router: Router) {}

url:string

 ngOnInit() {
    this.url = this.router.url;
    this.route.params.subscribe(params => {
      if (params['id']) {
        this.url = this.url.substr(0, this.url.lastIndexOf("\/"));
      }
    })
  }

您可以像这样尝试激活路线:

constructor(private activatedRoute: ActivatedRoute) { }

然后你可以检查路由中是否有 id 参数,并根据它你可以通过组合 URLSegments 来获取路由,如下所示:

let segmentLength = this.activatedRoute.snapshot.url.length;
let path = '/';
if (this.activatedRoute.snapshot.params['id']) {
  segmentLength--;
}

for (let i = 0; i < segmentLength; i++) {
  path += this.activatedRoute.snapshot.url[i].path + '/';
}
console.log(path);

在这种情况下,这是对我有用的代码。

import { Injectable } from '@angular/core';
import { Router, NavigationEnd } from '@angular/router';

@Injectable({
  providedIn: 'root'
})

export class NavigationService {

  constructor(
    private router: Router
  ) {

    this.router.events.subscribe((val) => {
      if (val instanceof NavigationEnd) {
        const urlTree = this.router.parseUrl(val.url);
        const urlSegments = urlTree.root.children['primary'].segments.map(segment => segment.path);
        const url = (`/${urlSegments[0]}/${urlSegments[1]}`);
      }
    });

  }

}