Angular - 使用HashLocationStrategy时,window.search和router.queryParams不匹配
创始人
2024-10-14 22:30:16
0

当使用HashLocationStrategy时,window.search和router.queryParams可能不匹配的原因是因为HashLocationStrategy将路由参数保存在URL的哈希部分,而不是查询字符串中。为了解决这个问题,你可以使用ActivatedRoute服务中的fragment属性。

下面是一个示例代码:

  1. 在你的组件中导入必要的模块和服务:
import { Component } from '@angular/core';
import { ActivatedRoute } from '@angular/router';

@Component({
  selector: 'app-my-component',
  template: `
    

Query Params: {{ queryParams }}

` }) export class MyComponent { queryParams: any; constructor(private route: ActivatedRoute) { this.queryParams = this.route.snapshot.queryParams; this.route.fragment.subscribe(fragment => { const params = new URLSearchParams(fragment); this.queryParams = params.toString(); }); } }
  1. 在你的路由模块中,将HashLocationStrategy设置为路由策略:
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { LocationStrategy, HashLocationStrategy } from '@angular/common';

const routes: Routes = [
  // your routes here
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule],
  providers: [{ provide: LocationStrategy, useClass: HashLocationStrategy }]
})
export class AppRoutingModule { }

通过使用ActivatedRoute服务中的fragment属性,我们可以获取到URL的哈希部分,并将其解析为查询字符串。然后,我们可以将解析后的查询参数赋值给组件中的queryParams属性,以便在模板中使用。

请注意,在这个示例中,我们使用了ActivatedRoute服务的snapshot属性来获取初始的查询参数,同时使用了fragment属性的订阅方法来获取动态更新的查询参数。如果你需要在组件中动态更新查询参数,你可以根据你的需求使用snapshot或subscribe方法。

相关内容

热门资讯

终于知道!wepoker私人局... 终于知道!wepoker私人局辅助器怎么用,哈糖大菠萝能开挂吗,揭秘教程(有挂技巧)1、玩家可以在w...
记者揭秘!德普之星辅助工具如何... 记者揭秘!德普之星辅助工具如何设置,hhpoker德州真的假的,揭秘教程(有挂软件)1、很好的工具软...
盘点一款!pokemmo手机脚... 盘点一款!pokemmo手机脚本辅助器,wepoker有辅助功能吗,解密教程(有挂辅助);建议优先通...
解密关于!wepoker辅助是... 1、解密关于!wepoker辅助是真的吗,wpk辅助器,AI教程(有挂技巧)。2、wepoker辅助...
推荐攻略!we-poker辅助... 推荐攻略!we-poker辅助,hhpoker有后台操作吗,切实教程(有挂辅助)关于hhpoker有...
每日必备!pokemmo手机版... 每日必备!pokemmo手机版透视脚本,wpk辅助器,透明教程(有挂神器);建议优先通过pokemm...
一分钟揭秘!hhpoker是正... 《一分钟揭秘!hhpoker是正规的吗,wepoker怎么挂底牌,玩家教你(有挂透明)》 hhpok...
我来教教大家!wepoker看... 我来教教大家!wepoker看底牌,约局吧德州可以透视吗,揭秘攻略(有挂透视)1、不需要AI权限,帮...
记者揭秘!epoker透视底牌... 记者揭秘!epoker透视底牌,大菠萝辅助器,2025教程(有挂方法);玩家必备必赢加哟《13670...
教程攻略!pokemmo辅助器... 1、教程攻略!pokemmo辅助器手机版下载,智星德州插件2024最新版,玩家教程(有挂技巧)2、进...