繁体   English   中英

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

[英]Get url path without parameters in Angular2+

有没有办法在没有参数的情况下获取url路径。

如果我在 RouterModule 中有这个:

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

我需要得到字符串

“/一二”

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

您可以尝试这样激活路由:

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

像这样尝试:

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

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

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

  }

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM