0

I was trying to find the difference between .snapshot and .queryParam in angular for the same i created a demo with the component code as follows

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

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

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

  ngOnInit(): void {
    const id =   this._route.snapshot.paramMap.get('id');
    let par:any;
    this._route.queryParams.subscribe((params) =>{
        par = params['id'];
    })
    console.log('id' + id)
    console.log('par' + par)
    this.router.navigate(['routed/:2'])
    console.log('id 2 ' + id)
    console.log('par 2' + par)
  }

}

the output that i get for the above code is

id1
parundefined
id 2 1
par 2undefined

Where would i be going wrong that i recieve undefined when i use subscribe

Swarup Chavan
  • 206
  • 1
  • 15

2 Answers2

0

The par variable is assigned asynchronously. As such, any statements that directly depend it's new state should be inside the subscription. Because by the time you're logging it, it isn't assigned any values yet.

  ngOnInit(): void {
    const id =   this._route.snapshot.paramMap.get('id');
    let par:any;
    this._route.queryParams.subscribe((params) =>{
        par = params['id'];
        console.log('par' + par)
        this.router.navigate(['routed/:2'])
        console.log('par 2' + par)
    })
    console.log('id' + id)
    console.log('id 2 ' + id)
  }

With the above statements, you might observe that the id logs are printed before the par logs. More info on asynchronous data here.

ruth
  • 29,535
  • 4
  • 30
  • 57
0
const id = this._route.snapshot.paramMap.get('id');

I think you are trying to get params not queryParams.

You should subscribe to params. And move your console.log for par variable inside the subscription because it's asynchronous.

this._route.params.subscribe((params) => {
  par = params['id'];
  console.log('par' + par);
});
this.router.navigate(['routed/:2']);
critrange
  • 5,652
  • 2
  • 16
  • 47