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

Angular加载JSON文件后跳转页面,数据未持久化问题排查

问题原因

你用window.location.href = "/planung"跳转时,会触发整页刷新,Angular应用会重新初始化。你的dataService如果是内存存储数据(默认情况),刷新后服务实例会重置,之前存入的数据自然就没了,所以跳转后页面看不到数据。

解决方案

改用Angular内置的Router服务进行路由跳转,它属于单页应用的无刷新跳转,不会重置应用状态:

  1. 在组件中注入Router服务:
import { Router } from '@angular/router';

constructor(private router: Router, private dataService: DataService) {} // 假设你的服务类名为DataService
  1. 替换跳转代码:
    把window.location.href = "/planung";改成:
this.router.navigate(['/planung']);

修改后的完整函数代码:

onFileSelected(event: any): void {
    const file = event.target.files[0];
    if (file) {
      this.dataService.resetAllData()
      const fileReader = new FileReader();
      fileReader.readAsText(file, 'UTF-8');
      fileReader.onload = () => {
        try {
          const json = JSON.parse(fileReader.result as string);
          this.allData = json;
          console.log('JSON-Daten geladen:', this.allData);
          this.dataService.setAllData(this.allData);
          // 改用Angular Router跳转
          this.router.navigate(['/planung']);
        } catch (e) {
          console.error('Fehler beim Parsen der JSON-Datei:', e);
        }
      };
      fileReader.onerror = (error) => {
        console.error('Fehler beim Lesen der Datei:', error);
      };
    }
  }
额外建议

如果之后需要支持页面刷新后数据不丢失,可以在dataService的setAllData方法里把数据存入localStorage或sessionStorage,在获取数据时从存储中读取:

// dataService中的示例代码
setAllData(data: any): void {
  this.allData = data;
  localStorage.setItem('appData', JSON.stringify(data));
}

getAllData(): any {
  const savedData = localStorage.getItem('appData');
  return savedData ? JSON.parse(savedData) : this.allData;
}

内容的提问来源于stack exchange,提问作者Michael Fischer

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 14:37:14