ActivatedRoute.queryParams is undefined

烂漫一生 提交于 2019-12-07 05:27:28

问题


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.


回答1:


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' } });
    }
}


来源:https://stackoverflow.com/questions/40362619/activatedroute-queryparams-is-undefined

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!