Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract id from URL using Angular (2+ till latest)

Tags:

angular

Hi I am trying to extract the id part of the URL using Angular2.

http://localhost:3000/item/187809

I have been playing around with ActiveRoute within onInit but without luck

     this.route.queryParams.forEach((params: any) => {
       console.log("QUERYPARAMS");
       console.log(params);
     });

Also tried subscribing to route change like this

    this.routeSub = this.route.queryParams.subscribe(params => {
       console.log(params);
       console.log(+params['id']);
    }); 

but params is just an empty object.

I am defining the route as a lazy route like this

    {
        path: item',
        children: [
           { path: ':id', loadChildren: './item/item.module#ItemModule'},
        ]
    },

I think the problem is that I have a header component and a main component which holds the lazy loaded routed child. I am trying to load the id inside the header component.

Any idea what's missing?

like image 330
doorman Avatar asked Mar 16 '17 15:03

doorman


People also ask

How do I get the URL of a component in angular?

Getting the URL parameters Consider, we have the following route in our angular routes array. const routes: Routes = [ { path: "product/:id", component: ProductComponent }, ]; To access the id (url) parameter value from a ProductComponent, we can use the ActivatedRoute interface this.route.params observable.

How to access the ID (URL) parameter value from a productcomponent in angular?

Consider, we have the following route in our angular routes array. To access the id (url) parameter value from a ProductComponent, we can use the ActivatedRoute interface this.route.params observable. Similarly, we can also use this.route.snapshot.params object.

How to get the URL parameters of a route in angular?

Getting the URL parameters. Consider, we have the following route in our angular routes array. const routes: Routes = [ { path: "product/:id", component: ProductComponent }, ]; To access the id (url) parameter value from a ProductComponent, we can use the ActivatedRoute interface this.route.params observable.

How to get data using angular services?

How To Get Data Using Angular Services 1 If we talk about AngularJS, in this, we have five ways to create service, but in Angular 2, we just have one way or... 2 This data is returned in the form of ‘PROMISES’ or ‘OBSERVABLE’ . 3 This SERVICE is decorated with @injectable . 4 Then use export service class to achieve it. More ...


4 Answers

Subscribing and Unsubscribing to Route Parameters

  1. Make sure you have configured a route that expects a parameter like so:
{path: 'item/:id', component: SomeItemComponent}
  1. Declare a variable for your route subscription. Import ActivatedRoute (not ActiveRoute) and inject it in your component constructor.
private routeSub: Subscription;
constructor(private route: ActivatedRoute) { }
  1. Inside ngOnInit in the same component, you can access the data in the params observable by subscribing to it like so:
ngOnInit() {
  this.routeSub = this.route.params.subscribe(params => {
    console.log(params) //log the entire params object
    console.log(params['id']) //log the value of id
  });
}
  1. Inside ngOnDestroy, unsubscribe to prevent memory leaks.
ngOnDestroy() {
  this.routeSub.unsubscribe();
}

Update - January 2021

There is a big difference between route.params and route.queryParams.

route.params, when subscribed to, returns an object with keys (that come from your route parameters, see step 1) and string values that are provided when navigating to the route. For example:

example.com/item/1

{
  itemId: '1'
}

route.queryParams, when subscribed to, returns an object with keys and string values that come from the query string (wiki) in the URL. For example:

example.com/welcome?var1=abc&var2=cde

{
  var1: 'abc',
  var2: 'cde'
}

route.queryParams will be undefined if a query string is not present in the URL. I believe OP, and some users in the comments have mistakenly used this instead of route.params.

like image 53
Chris Newman Avatar answered Oct 20 '22 17:10

Chris Newman


I know I'm a bit late with a reply, but just in case you were still having problem please take a look at the Angular documentation.

angular routing tutorial

Look at the example from the link.

Start by importing ActivatedRoute:

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

Then inject it in the constructor

    constructor(private route: ActivatedRoute) {}

And in OnInit()

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

and like this you don't need to worry about any Observables directly.

Hope this helps you.

like image 28
cgiacomi Avatar answered Oct 20 '22 19:10

cgiacomi


You have multi options to get id

    constructor(private route: ActivatedRoute) { }

1-With the help of params

    const id= this.route.snapshot.params['id'];

or

    const id = this.route.snapshot.params.id // any param name after "params"

2-With the help of paramMap

    const id= this.route.snapshot.paramMap.get('id')

3-subscribe to params (do not forget to unsubscribe)

      private subscription: Subscription

      constructor(private route: ActivatedRoute) { }
      ngOnInit(): void {
        this.subscription = this.route.params.subscribe(params => {
          const id = params['id']
        })
      }

     //To prevent memory leak
      ngOnDestroy(): void {
        if (this.subscription)
          this.subscription.unsubscribe()
      }

UPDATED

Imagine, you have the following route:
    {
      path: "",
      component: LayoutComponent,
      children: [
        {
          path: "action/:id", component: ChildComponent
        }
      ]
    }

If you are in the LayoutComponent and you want to get params of ChildComponent you have to use the following way:

    this.route.children.forEach(child => {
      child.params.subscribe(params => {
          const id = params['id']
      })
    }
like image 31
AbolfazlR Avatar answered Oct 20 '22 17:10

AbolfazlR


I suspect the issue is that you're using queryParams instead of just params.

params: An Observable that contains the required and optional parameters specific to the route.

queryParams: An Observable that contains the query parameters available to all routes.

so try this:

    this.route.params.subscribe(params => {
       console.log(params);
       console.log(+params['id']);
    });
like image 11
MattEnth Avatar answered Oct 20 '22 19:10

MattEnth