【问题标题】:How to keep shared data after page refresh in Angular?如何在 Angular 中刷新页面后保留共享数据?
【发布时间】:2020-06-20 14:07:35
【问题描述】:

我是 Angular 新手,正在寻找一种在页面刷新时维护共享数据的解决方案。

我有 2 个组件,即冷却器和配方。冷却器组件将选定的冷却器信息共享给配方组件。我在这里使用共享服务在 2 个组件之间传递数据。在配方组件出现导航数据后。页面刷新后,数据丢失。如何在页面刷新时/之后维护数据。

组件1(冷却器):

createQuotation(){
    this.selectedCoolers = [];
    for(let i=0; i< this.coolers.length; i++)
    {
      if(this.coolers[i].check)
      {
        this.selectedCoolers.push(this.coolers[i]);
      }
    }
    this.coolerservice.updateSelectedCoolers(this.selectedCoolers);
  }

共享服务(CoolerService)

updateSelectedCoolers(coolers : Cooler[]){
        console.log("From updateSelectedCoolers");
        console.log(coolers);
        this._selectedCoolersSource.next(coolers);
    }

成分2(配方):

selectedCoolers : Cooler[];
  constructor(private router: ActivatedRoute, private http: HttpClient, private coolerservice: CoolerService){}
  ngOnInit() {
    this.coolerservice.selectedCoolers$.subscribe(
      coolers => {
        console.log("In ngOnInit");
        console.log(coolers);
        this.selectedCoolers = coolers;
        console.log(this.selectedCoolers); //Line1
      }
    );
    console.log("After Navigation");
    console.log(this.selectedCoolers); //Line2
  }

selectedCoolers 有超过 50 个。 我想在页面刷新后将数据保留在 this.selectedCoolers 中。 还有'console.log(this.selectedCoolers); //Line2' 显示未定义。

【问题讨论】:

  • 您可以在获取数据后立即将数据保存在会话存储或本地存储中。
  • selectedCoolers 的数量已超过 50 个。将所有这些数据存储在本地/会话存储中是否是一种好方法?感谢您的快速回复。 :)
  • 本地存储最多可以存储 10MB 的数据,50 个数据点非常小,我认为这不是问题。
  • 将数据存储在会话存储中并且可以正常工作。但是这里的Service有什么用呢? sessionStorage.setItem 可以从 Component1 和 sessionStorage.getItem 从 Component2 完成。
  • 在下面添加了我的答案。

标签: angular typescript


【解决方案1】:

您可以在获得数据后立即将数据保存在会话存储本地存储中。

您最多可以在本地存储中存储 10MB 的数据,而 50 个数据点非常小,我认为这不是问题。

你当然可以从组件本身做到这一点,但如果它与组件无关,建议在服务中编写代码。现在您将数据存储在本地存储中,因此请使用服务。 它将使您的代码不那么混乱和可扩展。

假设您想在将来将它们存储到本地存储之前执行一些操作,您可以在服务类中轻松地做到这一点。随着应用程序的增长,隔离总是有帮助的。

希望对你有帮助。

【讨论】:

    【解决方案2】:

    您可以将数据设置为路由参数。重新加载后,您可以从 url 获取它。

    我们可以通过在路由器中使用 navigatenavigateByUrl 在您的 url 参数中附加数据。并且我们可以通过ActivatedRoute示例获取组件中的数据:

    this._ActivatedRoute.queryParams.subscribe((params: Params) => {
            if(params){
              // params is your data from last component
            }
    });
    

    无需服务即可将这些类型的数据从一个组件传递到另一个组件。

    你可以在url参数中设置数据

    this._Router.navigate([url],{queryParams:$objectvariable});
    

    【讨论】:

      猜你喜欢
      • 2017-03-05
      • 2021-08-21
      • 2019-02-19
      • 2014-07-24
      • 2017-11-05
      • 2011-08-23
      • 1970-01-01
      • 2023-03-28
      • 1970-01-01
      相关资源
      最近更新 更多