如何从Angular应用程序的URL片段中检索参数?

use*_*101 5 oauth angular

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

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

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

Bou*_*ule 5

您可以使用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
  }
Run Code Online (Sandbox Code Playgroud)

要检索查询参数,只需更换fragmentqueryParams这个代码。