Sabith
Sabith

Reputation: 1656

How to read data passed in routed url in component angular

I am new to angular 2+, and trying to learn.

I have a routes in angular like

const routes: Routes = [{path:"home",component:HomeComponent},                       
                        {path:"designer",component:DesignerComponent},
                        {path:"designer/:id",component:DesignerComponent}];

Once I reach on the DesignerComponent using the path designer/:id, I want to fetch the value "id". How can I do that? I am using latest version of angular.

Upvotes: 1

Views: 1643

Answers (3)

sibabrat swain
sibabrat swain

Reputation: 1368

You need to add ActivatedRoute and inside will have snapshot.paramMap you will get the parameter which you have passed.

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

private userId = '';
constructor(private route: ActivatedRoute){

}

ngOnInit() {
   this.userId = this.route.snapshot.paramMap.get('id');
}

OR

ActivatedRoute.paramMap property is an Observable map of route parameters. The paramMap emits a new map of values that includes id when the user navigates to the component. In ngOnInit you subscribe to those values and set the ID.

ngOnInit() {
  this.route.paramMap.pipe(
   switchMap(params => {
     // (+) before `params.get()` turns the string into a number
     this.userId = +params.get('id');
   })
 );
}

Upvotes: 3

Yajnesh Rai
Yajnesh Rai

Reputation: 310

It is better to subscribe to the route, so you get the values everytime the /:id changes.

Add this code in the constructor of DesignerComponentclass:

constructor(private route: ActivatedRoute){
    this.route.params.subscribe(data => this.userId = data['id'])
});

Upvotes: 0

jitender
jitender

Reputation: 10429

You can do it in two way first is

constructor(private route: ActivatedRoute){
  this.userId=this.route.params.snapshot['id']
}

Other way you can subscribe to params like

constructor(private route: ActivatedRoute){
      this.route.params.subscribe(data=>this.userId=data['id']
 })
    }

Go with second approach if your param can change while you are on the same root

Upvotes: 3

Related Questions