Angular中页面加载后查询参数被移除?
创始人
2024-10-31 20:01:43
0

这是因为浏览器在重新加载页面时,会清除掉URL中的查询参数。要解决这个问题,可以使用Angular的内置服务“ActivatedRoute”和“Router”来获取和持久化查询参数。

首先,在需要获取查询参数的组件中,注入“ActivatedRoute”和“Router”服务:

import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';

@Component({
  selector: 'app-my-component',
  templateUrl: './my-component.component.html',
  styleUrls: ['./my-component.component.css']
})
export class MyComponentComponent implements OnInit {

  constructor(
    private route: ActivatedRoute,
    private router: Router
  ) { }

  ngOnInit() {
    this.route.queryParams.subscribe(params => {
      console.log(params);
    });
  }

}

然后,在需要持久化查询参数的地方(如点击某个按钮后进行页面跳转),使用“Router”服务的“navigate”方法,并传入“queryParamsHandling”选项:

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';

@Component({
  selector: 'app-another-component',
  templateUrl: './another-component.component.html',
  styleUrls: ['./another-component.component.css']
})
export class AnotherComponentComponent implements OnInit {

  constructor(
    private router: Router
  ) { }

  ngOnInit() {
  }

  goToMyComponent() {
    this.router.navigate(['/my-component'], { queryParams: { param1: 'value1' }, queryParamsHandling: 'merge' });
  }

}

在这个示例中,“queryParamsHandling”选项设置为“merge”,意味着将新的查询参数与现有的查询参数进行合并。也可以将它设置为“preserve”,表示保留现有的查询参数并忽略新的查询参数。

通过这种方法,将可以持续获取和使用查询参数,而不用担心浏览器重新加载页面时会将它们清除掉。

相关内容

热门资讯

透视有挂"wepok... 透视有挂"wepoker轻量版辅助"都是是有辅助插件(哔哩哔哩)1、进入到wepoker轻量版辅助是...
透视解迷"wepok... 透视解迷"wepoker怎么买辅助"确实真的有辅助器(哔哩哔哩)一、wepoker怎么买辅助游戏安装...
透视必备"wpk软件... 透视必备"wpk软件是正规的吗"果然存在有辅助脚本(哔哩哔哩)1、下载好wpk软件是正规的吗脚本下载...
透视透视"We po... 透视透视"We poker辅助器下载"竟然真的是有辅助脚本(哔哩哔哩)1.We poker辅助器下载...
透视必备"wepok... 透视必备"wepoker透视版下载"都是有辅助器(哔哩哔哩)运wepoker透视版下载辅助工具,进入...
透视分享"聚星ai辅... 透视分享"聚星ai辅助工具下载"好像是有辅助工具(哔哩哔哩)在进入聚星ai辅助工具下载软件靠谱后,参...
透视有挂"hhpok... 透视有挂"hhpoker辅助挂是真的吗"真是真的是有辅助神器(哔哩哔哩)1、该软件可以轻松地帮助玩家...
透视解谜"智星德州插... 透视解谜"智星德州插件最新版本更新内容详解"切实真的有辅助脚本(哔哩哔哩)1、透视解谜"智星德州插件...
透视辅助"wepok... 透视辅助"wepoker底牌透视"都是是真的辅助神器(哔哩哔哩)1、用户打开应用后不用登录就可以直接...
透视辅助"wepok... 透视辅助"wepoker透视脚本苹果版"一直是有辅助方法(哔哩哔哩)1)wepoker透视脚本苹果版...