1

Is there a way to get url path without parameters.

If I have this inside RouterModule:

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

I need to get string

"/one/two"

for my NavigationService in both cases, with and without id.

2
  • You need to get that where? In the RouterModule? And what for? Seems like this question is missing some information. Commented Jul 13, 2019 at 20:06
  • I need it inside my SidenavComponent. Commented Jul 13, 2019 at 20:09

3 Answers 3

2

You can try activated route like this:

constructor(private activatedRoute: ActivatedRoute) { }

Then you can check if there is id param in the route or not and depending on that you can get the route by combining the URLSegments like this:

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);
Sign up to request clarification or add additional context in comments.

Comments

1

Try like this:

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

3 Comments

This code is working great but sometimes there is no id in url just '/one/two'. In that case it is not working. In that case it retunrs '/one'.
In that case you can check if the route has any param, only then get the substring
@IvanTanasijevic Updated the answer, please check
0

This is a code which worked for me in this case.

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

  }

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.