Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

193
Vistas
Parent components gets empty Params from ActivatedRoute

I have a main component that has a router-outlet in it. In the component that is loaded in the router-outlet I grab the url parameter like this:

ngOnInit(): void {
    // _route is injected ActivatedRoute
    this._route.params.subscribe((params: Params) => {
        if(params['url']){
          this.testUrl = params['url'].replace(new RegExp('\%2[fF]', 'g'), '/');

        }

    });
}

This works fine, but when I try it on my top level component the params object is always empty. I don't understand why as the nested components param object has the data in it and I am trying to access it exactly the same way. There are no errors to go on, the param object is just empty.

Why doesn't my parent component get the right Params object from ActivatedRoute?

edit:

as requested full parent component

import { OnInit, Component, Directive } from '@angular/core';
import { Router, ActivatedRoute, Params } from '@angular/router';
import { Observable } from 'rxjs/Observable';

@Component({
  selector: 'app-root',
  templateUrl: 'app.component.html',
})
export class AppComponent {
  public testUrl: string;
  constructor(private router: Router, private _route: ActivatedRoute) {

  }
  ngOnInit(): void{
    this._route.queryParams.subscribe((params: Params) => {
      console.log(params);

      if (params['url']) {
        this.testUrl = params['url'].replace(new RegExp('\%2[fF]', 'g'), '/');
        alert(params['url']);
      }
    });
  }

}

router code for app.module.ts:

RouterModule.forRoot([
  { path: '', component: CheckMobileComponent },
  { path: '**', component: CheckMobileComponent }
]),

router code for nested module:

RouterModule.forChild([
 { path: 'report', component: MobileReportComponent }

There is no directly specified route for my app.component as it is loaded by a selector in index.html.

about 4 years ago · Santiago Trujillo
3 Respuestas
Responde la pregunta

0

ActivatedRoute: Contains the information about a route associated with a component loaded in an router outlet. If you would like to access route details outside of it, use the code below.

import { Component } from '@angular/core';
import { Router, ActivatedRoute, Params, RoutesRecognized } from '@angular/router';

export class AppComponent {

    constructor(private route: ActivatedRoute, private router: Router) {

    }

    ngOnInit(): void {
        this.router.events.subscribe(val => {

            if (val instanceof RoutesRecognized) {

                console.log(val.state.root.firstChild.params);

            }
        });

    }
}

There are other ways to share data in between components for example by using a service.

For more details about how you can tackle this as concept, read comments here.

about 4 years ago · Santiago Trujillo Denunciar

0

The Very simple answer

import { Component } from '@angular/core';
import { Router, ActivatedRoute, Params, RoutesRecognized } from '@angular/router';

export class AppComponent {

    constructor(private actRoute: ActivatedRoute, private router: Router){}

    ngOnInit(): void {
        this.actRoute.firstChild.params.subscribe(
            (params: any) => {
                if (params.hasOwnProperty('<whatever the param name>') != '') {
                    //do whatever you want
                    console.log(params.<whatever the param name>);
                } 
            });
    }
}
about 4 years ago · Santiago Trujillo Denunciar

0

If you'd like to access the router parameters via a service, this approach will not work! consider using a service to prevent the replication of the "Route params value extraction logic" (from this Medium article):

@Injectable({
  providedIn: 'root'
})
export class MyParamsAwareService {
  constructor(private router: Router) { 
    this.router.events
      .pipe(
        filter(e => (e instanceof ActivationEnd) && (Object.keys(e.snapshot.params).length > 0)),
        map(e => e instanceof ActivationEnd ? e.snapshot.params : {})
      )
      .subscribe(params => {
      console.log(params);
      // Do whatever you want here!!!!
      });
  }
}
about 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda