在Angular2 +中获取不带参数的网址路径

时间:2019-07-13 20:03:25

标签: angular angular2-routing

有没有一种方法可以获取不带参数的网址路径。

如果我在RouterModule中具有此功能

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

我需要获取字符串

  

“ /一个/两个”

对于这两种情况,无论有无ID,都适用于我的NavigationService。

3 个答案:

答案 0 :(得分:1)

尝试这样:

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("\/"));
      }
    })
  }

答案 1 :(得分:1)

您可以尝试如下激活路线:

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

答案 2 :(得分:0)

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

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]}`);
      }
    });

  }

}