20

I want to get the last part of my url for example from /item/:id/edit I want to get edit or /edit.

I found this Question here but this doesnt work because I want to run this Code in the parent component and the whole url I get from this Code is /item/:id.

How can I get the last part from it?

LastChar23
  • 449
  • 1
  • 4
  • 15
  • check this..https://stackoverflow.com/questions/42483570/angular-2-get-parent-activated-route?noredirect=1&lq=1 – sp_m Jan 13 '20 at 12:40
  • Isn`t this a solution if I wanted to get the parent url? I can get this to with my linked question but I want the last part of the url – LastChar23 Jan 13 '20 at 12:43
  • if you don't need to subscribe on url changes you can get it from window.location.href. Something like: window.location.href split('/').[window.location.href split('/').lenght -1] – Marcel Hoekstra Jan 13 '20 at 12:44
  • What do you mean of `parent` component? – Ling Vu Jan 13 '20 at 12:53
  • Using `private activatedRoute: ActivatedRoute` should always give you the current path, no matter where you are – Ling Vu Jan 13 '20 at 12:54
  • Check this: https://stackoverflow.com/questions/4758103/last-segment-of-url – Juan Antonio Jul 31 '20 at 09:38

7 Answers7

21

I have the solution for getting the last part of URL

url = '/item/:id/edit'
url.split('/').pop();

Explain:

  1. .split('/') means split the string which is separated by '/' to an array of substrings
  2. .pop() means removes the last element of an array, and returns that element
  3. .split('/').pop() means split the string which is separated by '/' to an array of substrings then removes the last element of an array and return that element

I hope this help

Venusssss
  • 488
  • 1
  • 3
  • 11
16

You can use ActivatedRoute interface, it contains the router state tree within the angular app’s memory.

The parent property represents the parent of the route in the router state tree, while the snapshot property is the current snapshot of the route and url is an observable of the URL segments and it matched by this route.

Step 1: Import ActivatedRoute

    import { ActivatedRoute } from '@angular/router';

Step 2: Inject ActivatedRoute in constructor.

    constructor(private route: ActivatedRoute) { }

Step 3: Call it in Oninit lifecycle hook

      constructor(private route: ActivatedRoute){}
        
           ngOnInit() {
              this.route.parent.snapshot.url[2].path;
           }
HV Sharma
  • 4,891
  • 3
  • 15
  • 30
FedG
  • 1,218
  • 1
  • 5
  • 14
5

Since you want to get the URL part being in a parent component, you have to wait until the navigation occurs.

Get the last URL part from a parent component

router.events
  .pipe(
    filter(event => event instanceof NavigationEnd),
    map((event: NavigationEnd) => event.url)
  )
  .subscribe(url => {
    const lastUrlSegment = url.split('?')[0].split('/').pop()
  });

Where router is an injected Angular Router service. Here url.split('?')[0] returns the URL part without query parameters in case they exist, then split('/').pop() returns the last URL segment without the / character.

In case you'd like to

Get the last URL part from the child component

You could do that synchronously

const lastUrlSegment = router.url.split('?')[0].split('/').pop()

Where router is an injected Angular Router service. Pay attention, that under the child component I mean the one, rendered by the last URL segment we're looking for.

Andriy Chuma
  • 364
  • 4
  • 7
3
Use the below code.

My url is - localhost:4200/home/user/address

export class HomeComponent implements OnInit {

  constructor(private router: Router) {
    console.log(this.router.url)
    console.log(this.router.url.split('/')[0]);
    console.log(this.router.url.split('/')[1]);
    console.log(this.router.url.split('/').pop());
  }
}

Output -
>home/user/address
>home
>user
>address
  • Please don't post code-only answers but add a little textual explanation on how and why your approach works and how it differs from the other answers given. – ahuemmer Jul 18 '22 at 09:35
1

Another way is you can split the current url on the basis of '/', it will convert the url into an array and you can get any part you want. See the code snippet below:

url =window.location.href;

console.log(this.url.split('/')[4]);
Faisal Mushtaq
  • 485
  • 4
  • 11
  • I actually had to use this. I know it's not Angular-like, but the last section of the URL isn't being passed in the route for some reason. – Wayne F. Kaskie Dec 20 '22 at 01:08
1

This is what's working for me on Angular v15

export class OrderComponent {

  requestId: string | null = null;

  constructor(
    private route: ActivatedRoute,
  ) { }

  ngOnInit(): void {
    this.requestId = this.route.snapshot.paramMap.get('id');
  }

}

In the Routes I've

  {
    path: 'order/:id',
    component: OrderComponent,
    data: {
      breadcrumb: '',
    },
  },
Rami Alloush
  • 2,308
  • 2
  • 27
  • 33
0

As already said, you will need to use ActivatedRoute to do this, please see code example below:

constructor(private route: ActivatedRoute){
   var url = this.route.parent.snapshot.url[2].path;

   console.log(url);
}
Lewis Browne
  • 904
  • 7
  • 23