【问题标题】:ActivatedRoute.queryParams is undefinedActivatedRoute.queryParams 未定义
【发布时间】:2017-03-14 17:49:25
【问题描述】:

我正在尝试使用 Angular 2.0 捕获查询字符串参数,但遇到了困难。我有一个这样的网址

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

并且我希望能够在路由占据之前捕获 id_token 的值并且我丢失了参数。我找到了这个 GitHub 问题主题

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

但这使用了不再有效的弃用方法。我尝试了以下方法

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

我已经在构造函数以及组件的 ngOnInit() 中尝试过这些方法,但控制台总是显示未定义。我在错误的地方这样做吗?我根本无法更改 QS,因为它是由 Azure AD 创建的。

【问题讨论】:

    标签: angular routing


    【解决方案1】:

    尝试注入 ActivatedRoute 并使用 route.snapshot.queryParams['name'] 获取 queryParam,如下所示:

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

    通过 router.navigate 设置 queryParams 的工作方式如下:

    class SomeComponent {
        constructor(private router: Router) { }
        goSomewhere(): void {
            this.router.navigate(['somewhere'], { queryParams: { name: 'value' } });
        }
    }
    

    【讨论】:

    • 我遇到了类似的问题。我已经尝试了OP提出的所有内容以及您所说的内容。我不知道 OP 是否与我有同样的问题,但我正在以登录回调的形式到达我的路线,而不是从应用程序中的其他地方导航。我的 url 是 http://myhost/?code=1234#/auth/callback,在组件实例化之前,路由器会快速重新路由到 http://myhost/#/auth/callback
    • @JonTinsman 你解决了吗?我正面临着确切的问题
    • @masterfan 我不得不删除哈希导航。我的问题的原因是当身份验证服务器构建重新路由时,它没有将code 添加到末尾,而是使用了一个将哈希放在查询参数之后的构建器。主要开发人员使用哈希导航的最初原因似乎不再需要,并且在我们使用 http://myhost/auth/callback?code=1234 之后它就起作用了,然后我就能够通过 activatedRoute.snapshot.queryParams['code'] 访问查询参数
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-08-12
    • 1970-01-01
    • 2010-10-21
    • 2019-12-12
    • 2018-09-08
    • 1970-01-01
    相关资源
    最近更新 更多