You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular中如何获取URL锚点(#)后的参数值?

Angular中获取URL哈希(#)后的参数值

你遇到的问题是因为URL里的参数位于哈希片段(#之后的部分),而ActivatedRoute.queryParams仅能获取?开头的查询参数,所以返回空对象是正常的。以下是两种标准的获取方式:

方式一:通过ActivatedRoute监听哈希片段并解析

利用ActivatedRoute.fragment订阅哈希变化,再手动将片段解析为键值对:

import { ActivatedRoute } from '@angular/router';
import { map } from 'rxjs/operators';

constructor(private route: ActivatedRoute) {}

ngOnInit() {
  this.route.fragment.pipe(
    map(fragment => {
      if (!fragment) return {};
      // 解析哈希片段为参数对象
      return fragment.split('&').reduce((params, param) => {
        const [key, value] = param.split('=');
        params[key] = decodeURIComponent(value);
        return params;
      }, {} as Record<string, string>);
    })
  ).subscribe(params => {
    const param2Value = params['param2'];
    console.log(param2Value); // 输出 value2
  });
}

方式二:直接解析window.location.hash

如果不需要监听哈希变化,只是一次性获取参数,可以直接操作window.location.hash:

ngOnInit() {
  const hashContent = window.location.hash.slice(1); // 移除开头的#
  const params = hashContent.split('&').reduce((acc, curr) => {
    const [key, val] = curr.split('=');
    acc[key] = decodeURIComponent(val);
    return acc;
  }, {} as Record<string, string>);
  
  const param2Value = params['param2'];
  console.log(param2Value); // 输出 value2
}

注意:如果你的项目使用了HashLocationStrategy路由模式,上述方法依然有效,因为这里解析的是哈希片段内部的参数,而非路由本身的哈希路径。

内容的提问来源于stack exchange,提问作者Sai Ram

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 12:35:19