1
votes

Obtenez le chemin de l'url sans paramètres dans Angular2 +

Existe-t-il un moyen d'obtenir le chemin de l'url sans paramètres.

Si j'ai ceci dans RouterModule:

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

J'ai besoin d'obtenir une chaîne

"/ un / deux"

pour mon NavigationService dans les deux cas, avec et sans identifiant.


2 commentaires

Vous devez obtenir ça où? Dans le RouterModule? Et pour quoi faire? Il semble que cette question manque d'informations.


J'en ai besoin dans mon composant Sidenav.


3 Réponses :


1
votes

Essayez comme ceci:

constructeur (routeur privé: routeur) {}

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 commentaires

Ce code fonctionne très bien mais parfois il n'y a pas d'identifiant dans l'url juste «/ one / two». Dans ce cas, cela ne fonctionne pas. Dans ce cas, il revient '/ one'.


Dans ce cas, vous pouvez vérifier si la route a un paramètre, puis obtenir la sous-chaîne


@IvanTanasijevic a mis à jour la réponse, veuillez vérifier



2
votes

Vous pouvez essayer la route activée comme ceci:

constructeur (private enabledRoute: ActivatedRoute) {}

Ensuite, vous pouvez vérifier s'il y a un paramètre id dans la route ou non et en fonction de cela, vous pouvez obtenir l'itinéraire en combinant les URLSegments comme ceci:

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


0 commentaires

0
votes

C'est un code qui a fonctionné pour moi dans ce cas.

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

  }

}


0 commentaires