Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ActivatedRoute.queryParams is undefined

I am trying to capture a querystring parameter using Angular 2.0 and am having a hard time. I have a url like so

http://localhost:5000/?id_token=eyJ0eXAiO....

And I want to be able to capture the value of id_token before routing takes hold and I lose the parameter. I found this GitHub Issue Thread

https://github.com/angular/angular/issues/9451

But this uses a deprecated method that no longer works. I have tried the following methods

    var foo = this.activatedRoute.queryParams.subscribe(params => {
        console.log(params);
        let id = params['id_token'];
        console.log(id);
    });


   console.log(this.router.routerState.snapshot.root.queryParams["id_token"]);

   var bar = this.activatedRoute.params.subscribe(
        (param: any) => console.log(param['id_token']));

I have tried these methods in the constructor as well as ngOnInit() of my component, but the console always shows undefined. Am I doing this in the wrong place. I am not able to change the QS at all because it is being created by Azure AD.

like image 760
Isaac Levin Avatar asked Nov 01 '16 14:11

Isaac Levin


People also ask

What is query param in angular?

The query parameters feature in Angular lets you pass the optional parameters while navigating from one route to another. When you pass a query parameter to a specific route, it looks something like this, http://localhost:4200/orders?

What is ActivatedRoute?

The ActivatedRoute is the API that holds observable data that you can use to react to events with. You can subscribe to specific observable properties to get data from it asynchronously. The ActivatedRoute also contains ActivatedRouteSnapshot.


1 Answers

Try injecting ActivatedRoute and get the queryParam with route.snapshot.queryParams['name'] like this:

class SomeComponent implements OnInit {
    constructor(private route: ActivatedRoute) { }
    ngOnInit(): void {
        let value = this.route.snapshot.queryParams['name'];
    }
}

Setting the queryParams via router.navigate works like this:

class SomeComponent {
    constructor(private router: Router) { }
    goSomewhere(): void {
        this.router.navigate(['somewhere'], { queryParams: { name: 'value' } });
    }
}
like image 56
Simon Zyx Avatar answered Sep 22 '22 19:09

Simon Zyx