Angular同路由调用时参数未保存问题求助
问题原因
当通过router.navigate重新导航到当前组件时,组件会被重新初始化,原先在Select方法中设置的Filter.FilterType值会因为组件实例重建而丢失,导致ngOnInit中读取到的是null。
解决方案
方案1:通过路由参数传递筛选值
这种方式依赖路由传递状态,不受组件重建影响:
- 修改
search方法,将筛选值作为查询参数传入路由:
search() { this.router.navigate(['search'], { queryParams: { filterType: this.Filter.FilterType } }); }
- 在
ngOnInit中从路由参数读取筛选值并赋值:
ngOnInit(): void { this.pagetype = this.route.snapshot.routeConfig.path; if (this.pagetype === 'search') { // 从路由查询参数获取筛选值 const filterType = this.route.snapshot.queryParams['filterType']; if (filterType) { this.Filter.FilterType = filterType; } this.searchFilter(); } }
方案2:用单例服务保存筛选状态
将筛选状态放到全局单例服务中,组件重建后服务状态不会丢失:
- 创建筛选服务:
import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class FilterService { filterType: string | null = null; }
- 在组件中注入服务并修改相关方法:
// 组件构造函数注入服务 constructor(private filterService: FilterService) {} Select(data){ // 将值存入服务 this.filterService.filterType = data; } searchFilter() { // 从服务读取值 FilterJson.FilterType = this.filterService.filterType; }
额外检查
确保组件中已正确初始化Filter对象,避免初始值未定义:
// 组件类中声明 Filter = { FilterType: null };
内容的提问来源于stack exchange,提问作者user3653474
相关产品推荐
相关产品推荐

