【问题标题】:How to retrieve parameters from URL fragment in Angular application?如何从 Angular 应用程序中的 URL 片段中检索参数?
【发布时间】:2018-04-19 15:04:01
【问题描述】:

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

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

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

【问题讨论】:

  • 构造函数(私有路由:ActivatedRoute,私有路由器:Router){ this.route .queryParams .subscribe(params => { console.log(params ); }); } 你能在你的根组件中试试这个吗
  • @user183101 你解决过这个问题吗?
  • 如果你想在queryParams中使用fragment,应该是这样的:localhost/authentication?access_token={0}&expires_in={1}&user_id={2}#fragment_1

标签: angular oauth


【解决方案1】:

您可以使用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

【讨论】:

  • 如果我没记错的话,你的代码对我不起作用,因为我的 URL 中的参数在片段中。见this comment
  • 它适用于片段和查询参数。但是您的 url 似乎是错误的,您的 &params 没有第一个 ?params,所以也许 angular 无法以这种方式获取 queryParams
  • 根据 OAuth 规范,URL 是正确的。看来Angular无法解析片段中的参数
  • 好的,我明白了问题所在。这里可能有一个解决方案:stackoverflow.com/questions/36665234/…
【解决方案2】:
import {Router, ActivatedRoute, Params} from '@angular/router';
import {OnInit, Component} from '@angular/core';

@Component({...})
export class MyComponent implements OnInit {

  constructor(private activatedRoute: ActivatedRoute) {}

  ngOnInit() {
    // subscribe to router event
    this.activatedRoute.params.subscribe((params: Params) => {
        let userId = params['user_id'];
        console.log(userId);
      });
  }

}

如果要获取查询参数,请将this.activatedRoute.params替换为this.activatedRoute.queryParams

【讨论】:

  • 请参阅我上面介绍的 URL。据我了解,您的解决方案适用于没有片段的情况(URL 中没有符号“#”)。就我而言,我在控制台中使用您的代码得到“未定义”。
  • 好的。那么我认为你将不得不使用纯 javascript 方法来解析这样的 URL。在 Angular 中,没有这样的方法可以做到这一点。你也可以看到这个答案stackoverflow.com/a/40058721/4865392
【解决方案3】:
constructor(private activatedRoute: ActivatedRoute) {

    const fragment = activatedRoute.snapshot.fragment;

    const parts = fragment.split('&');

    const params = parts.reduce((map, part) => {
        const pieces = part.split('=');
        map[pieces[0]] = pieces[1];
        return map;
    }, {});

    console.log(params);
}

【讨论】:

    猜你喜欢
    • 2022-12-25
    • 1970-01-01
    • 1970-01-01
    • 2016-08-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-27
    相关资源
    最近更新 更多