Search code examples
angularurlpathuristring-parsing

How do you get the first part of a URI in Angular 5?


I have a button on my navbar. When clicked, I want a different behavior depending on which URI the user is currently on.

Let's say that I have this URI localhost:8080/entity/{entityId} How can I get entity, the first part of the URI, as a string in Angular 5.


Solution

  • Ok I found the answer from Angular's doc, you have to use the UrlSegment Angular class from @angular/router to parse the url in segments link to the relevant doc: https://angular.io/api/router/UrlSegment

    const tree: UrlTree = router.parseUrl('/team;id=33');
    const g: UrlSegmentGroup = tree.root.children[PRIMARY_OUTLET];
    const s: UrlSegment[] = g.segments;
    s[0].path; // returns 'team'
    s[0].parameters; // returns {id: 33}