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

查看:87
本文介绍了如何从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:

  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天全站免登陆