1

Okay so I am creating a simple page which i want the user to pass in a bunch of parameters via the URL. The very basic example I have been using is http://localhost:4200/?client_id=test

I am following all the procedures I can find on the internet but for some reason the parameters aren't available OnInit, and are only available via subscription?

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit{
  title = 'Login';
  submitted: boolean = false;

  constructor(
    private route: ActivatedRoute){
  }

  ngOnInit(){
    console.log(this.route.snapshot.queryParams); //line 26
    this.route.queryParamMap.subscribe(params => {
      console.log(this.route.snapshot.queryParams); //line 28
    })
  }
}

this is what prints

{} - line 26
{} - line 28
{client_id: "test"} - line 28

Its as if Angular isn't recognizing the query string parameters until after the page loads? How can i get around this?

Edit:

Ive tried using params.get() also - same result

this.route.queryParamMap.subscribe(params => {
  console.log(params.get('client_id'));
})

prints

null
test

so the first activation of the subscription the value is null - then the value changes to test and its updated. I'm trying to avoid the first "null" value.

Matt Goodis
  • 393
  • 1
  • 3
  • 11

3 Answers3

0

try this :

this.route.params.subscribe((params:Params) => {
    ... use params['key'] to access its value
});

in my opinion, the best approach is to use subscription and do like this :

enter image description here

Saeed Gholamzadeh
  • 932
  • 1
  • 6
  • 22
0

and try this one ...

@Component(/* ... */)
export class UserComponent implements OnInit {
    id$: Observable<string>;
    id: string;

    constructor(private route: ActivateRoute) {}

    ngOnInit() {
        this.id$ = this.route.paramMap.pipe(map(paramMap => paramMap.get('id')));

        // or for sync ( one time ) retrieval of id

        this.id = this.route.snapshot.paramMap.get('id');
    }
}
Saeed Gholamzadeh
  • 932
  • 1
  • 6
  • 22
0

both of these solutions are working if I try it:

 ngOnInit(){
    this.route.queryParamMap.subscribe(params =>
        console.log(params.get("client_id"))
     );

    this.route.queryParams.subscribe(params =>
        console.log(params["client_id"])
    );
 }
pero_hero
  • 2,881
  • 3
  • 10
  • 24