Angular 4 routing params captured as undefined

14,154

Solution 1

According to the official Angular guide, the use of params is discouraged. Instead, the suggestion is to use paramMap instead:

Two older properties are still available. They are less capable than their replacements, discouraged, and may be deprecated in a future Angular version.

params — An Observable that contains the required and optional parameters specific to the route. Use paramMap instead.

queryParams — An Observable that contains the query parameters available to all routes. Use queryParamMap instead.

To use paramMap, replace your ngOnInit with the following:

ngOnInit() {
  this.activatedRoute.paramMap.subscribe(params => {
    console.log(params.get('id'));
  });
}

I realise this isn't a direct fix for your issue, but I'm interested to see if it works for you. I would've written this as a comment but it would've been hard to read.

Solution 2

Got what was wrong, or at least got it to work.

Changed my routing definitions to:

const routes = [
  { path: '', component: NavigateComponent },
  { path: 'field', component: FieldComponent },
  { path: 'book/:id_book', component: MaterialEditComponent },
  { path: 'edit/:id', component: MaterialEditComponent },
  { path: '**', redirectTo: '/'}
];

Apparently, using 'children' does it not good.

Share:
14,154
Jocho Delgado
Author by

Jocho Delgado

Developer and IT enthusiast/professional.

Updated on June 05, 2022

Comments

  • Jocho Delgado
    Jocho Delgado over 1 year

    I'm new at Angular. I'm attempting to edit an item at localhost:4200/edit/:id but I can't capture the :id param to fetch the corresponding number from it (it is supposed to be something like localhost:4200/edit/7, for example). When I output the params.id to console, it always shows "undefined".

    My app.module.ts

    ...
    import { RouterModule} from '@angular/router';
    
    const routes = [
    { path: '', component: NavigateComponent },
    { path: 'field', component: FieldComponent },
    { path: 'book', component: MaterialFullComponent, children: [
      { path: '', redirectTo: '', pathMatch: 'full' },
      { path: ':id_book', component: MaterialFullComponent }
    ] },
    { path: 'edit', component: MaterialEditComponent, children: [
      { path: '', redirectTo: '', pathMatch: 'full' },
      { path: 'new', component: MaterialEditComponent },
      { path: ':id', component: MaterialEditComponent }
    ] },
    { path: '**', redirectTo: '/'}
    ];
    
    @NgModule({
      declarations: [
        AppComponent,
        AppLoginComponent,
        NavigateComponent,
        MaterialEditComponent,
        MaterialFullComponent,
        FieldComponent,
        MaterialComponent
      ],
      imports: [
        BrowserModule,
        FormsModule,
        RouterModule.forRoot(routes)
      ],
      providers: [
        MarcService,
        BookService,
        BookDetailService
      ],
      bootstrap: [AppComponent]
    })
    

    My MaterialEditComponent

    import { Component, OnInit } from '@angular/core';
    import { ActivatedRoute } from '@angular/router';
    import { BookService } from '../book.service';
    
    @Component({
      selector: 'app-material-edit',
      templateUrl: './material-edit.component.html',
      styleUrls: ['./material-edit.component.css']
    })
    
    export class MaterialEditComponent implements OnInit {
      activatedRoute: ActivatedRoute;  
      bookService: BookService;
      selectedBook = {  id_book: null, 
                    numero_ejemplares: null, 
                    autor: '', 
                    titulo: '',
                    editorial: '',
                    fecha_publicacion: '',
                    portada: ''
      };
    
      constructor(activatedRoute: ActivatedRoute, bookService: BookService) {
        this.activatedRoute = activatedRoute;
        this.bookService = bookService;
      }
    
      ngOnInit() {
        this.activatedRoute.params.subscribe(
          (params) => {
            console.log(params.id);
          }
        );
      }
    }
    
    • Younis Ar M
      Younis Ar M over 6 years
      Try accessing the id using ['id'] ie console.log(params['id']);
    • Jocho Delgado
      Jocho Delgado over 6 years
      Tried it, still nothing.
    • jonrsharpe
      jonrsharpe over 6 years
      I don't think it's helping to define component and children on the same route. Also note you can use parameter properties to simplify your definition, see typescriptlang.org/docs/handbook/classes.html
    • Younis Ar M
      Younis Ar M over 6 years
      can you create a plunker demo for your issue , that can give a better idea of the problem
  • Gel
    Gel over 3 years
    still getting undefined. Most docs I see were forcing me to use routerLink but I know we can capture the /:id onInit. oh well , keep searching