Search code examples
angular

Why queryParams are empty


I'm currently trying to understand how to collect the queryParameters in an Angular component. As I want to only collect them once during the init, I firstly tried the snapshot pattern:

ngOnInit() {
    console.log(this.route.snapshot.queryParamMap);
    console.log('param test = ' + this.route.snapshot.queryParamMap.get('test'));
}   

See the demo on Stackblitz: https://stackblitz.com/edit/angular-2tuafn Testable through the folowwing URL: https://angular-2tuafn.stackblitz.io?test=123

But as a result, the queryParam "test" is null and the queryParamMap is empty, see console output:

ParamsAsMap {params: {…}}
    keys: Array(0)
    params: {}
    __proto__: Object
param test = null

=> Why does the queryParamMap is empty ???

Then, I tried with the Observable pattern:

ngOnInit() {
    this.route.queryParamMap.subscribe(
      (params: ParamMap) => {
        console.log(params);
        console.log('param test = ' + params.get('test'));
      }
    );
}

See the demo on Stackblitz: https://stackblitz.com/edit/angular-hfqx8a Testable through the folowwing URL: https://angular-hfqx8a.stackblitz.io?test=123

But as a result, the queryParam "test" is firstly null and then it take the correct value (123), see console output:

ParamsAsMap {params: {…}}
    keys: Array(0)
    params: {}
    __proto__: Object
param test = null
Angular is running in the development mode. Call enableProdMode() to enable the production mode.
ParamsAsMap {params: {…}}
    keys: Array(1)
    params: {test: "123"}
    __proto__: Object
param test = 123

=> Why there is a first console output empty and then the console output with the correct queryParam value ?

After several researsh I don't reach to understand what's going on :-(

=> Thanks in advance for your help

Regards

EDIT:

Thanks to Dimanoid and Pravin Pokharkar, I understood my issue. => Because component is loaded before the actual routing applied!!!

Thus I have update my code an now I properly collect the queryparams:

this.router.events.subscribe(
  (event: RouterEvent) => {
    if (event instanceof NavigationEnd) {
        this.test = parseInt(
              this.activatedRoute.snapshot.queryParamMap.get('test')
        );
    }
  }
);

Solution

  • Because component is loaded before the actual routing applied. Add { enableTracing: true } to the RouterModule to see what is happening behind the scene.

    RouterModule.forRoot([], { enableTracing: true })
    

    https://stackblitz.com/edit/angular-boghpy?file=src/app/app.module.ts