如何从 Angular 应用程序中的 URL 片段中检索参数? [英] How to retrieve parameters from URL fragment in Angular application?

查看:13
本文介绍了如何从 Angular 应用程序中的 URL 片段中检索参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的 Angular 应用程序中使用 OAuth 隐式流身份验证方法.要检索访问令牌,我需要从以下字符串解析参数:

I use OAuth Implicit flow authentication method in my Angular application. To retrieve access token I need to parse parameters from following string:

http://localhost/authentication#access_token={0}&expires_in={1}&user_id={2}

经过一番调查,我没有找到任何从这些 URL 中检索参数的机制(我发现的所有机制都基于使用手动字符串拆分.这是否意味着 Angular 没有开箱即用"的解析机制?来自 URL 片段的参数,最好的方法是使用 substring()split() 方法?

After some investigation I did not find any mechanisms to retrieve parameters from such URLs (all mechanisms which I found are based on using manual string splitting. Does it mean that Angular doesn't have "out of the box" mechanisms to parse parameters from URL fragment and the best way to do this is use substring() or split() method?

推荐答案

您可以使用 ActivatedRoute 来实现:

You can do it using the ActivatedRoute :

  constructor(private route: ActivatedRoute) {}

  ngOnInit() {
    console.log(this.route.snapshot.fragment); // only update on component creation
    this.route.fragment.subscribe(
      (fragments) => console.log(fragments)
    ); // update on all changes
  }

要检索查询参数,只需将此代码中的 fragment 替换为 queryParams.

To retrieve query parameters, just replace fragment by queryParams on this code.

这篇关于如何从 Angular 应用程序中的 URL 片段中检索参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆