Yoann Picquenot
Yoann Picquenot

Reputation: 650

ANGULAR params object null using activatedRoute

I have a problem trying to get an :id parameters

Here's my route:

{
    path: 'user',
    component: UserComponent,
    children: [
      {
        path: ':id',
        component: UserComponent
      }
    ]
},

And here's my component:

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

@Component({
  selector: 'app-user',
  templateUrl: './user.component.html',
  styleUrls: ['./user.component.css']
})
export class UserComponent implements OnInit {

  constructor(private route: ActivatedRoute) { }

  ngOnInit() {
    this.getUser();
  }

  getUser() {
    this.route.params.subscribe(params => {
      console.log(params); // displays empty object
    });
  }

}

Am I doing it wrong to get paramters?

Thank you!

PS Any criticism or advice on my code is the very welcomed!

Upvotes: 0

Views: 791

Answers (1)

Vivek Doshi
Vivek Doshi

Reputation: 58523

You are loading same Component as Child , that's kind of wiered

For that your code should look like

{
    path: 'user/:id',
    component: UserComponent
}

OR

{
    path: 'users', 
    component: UserComponent, // For showing list of users
    children: [
      {
        path: ':id', 
        component: UserDetailComponent // For Showing detail of specific user
      }
    ]
},

Upvotes: 2

Related Questions