用户按下后退按钮或刷新页面时,如何保持应用的搜索过滤器?

时间:2019-10-22 13:04:41

标签: javascript angular

我在页面上创建了一个搜索引擎,用户可以在其中应用一些过滤器。基本上,我要做的是添加列表中的过滤器,然后自动将参数添加到URL。

  applyFilters(formValue: any) {

    this.filterList = new Array();
    this.appliedFilters = 0;
    this.filtersStr = '';

    if (formValue.active != null) {
      this.appliedFilters++;
      this.buildStringFilter('active=' + this.activeSelected.value);
      this.filterList.push(new Filter('active', 'active: ' + this.activeSelected.descricao));
    }

    if (formValue.idLaboratory != null) {
      this.appliedFilters++;
      this.buildStringFilter('laboratory.id=' + this.labSelected.id);
      this.filterList.push(new Filter('idLaboratory', 'Laboratory: ' + this.labSelected.nome));
    }

    if (formValue.idOwner != null) {
      this.appliedFilters++;
      this.buildStringFilter('owner=' + this.ownerSelected.idUsuario);
      this.filterList.push(new Filter('idOwner', 'Owner: ' + this.ownerSelected.nome));
    }

    if (formValue.machineName != null) {
      this.appliedFilters++;
      this.buildStringFilter('machineName=ci(contains(' + formValue.machineName + '))');
      this.filterList.push(new Filter('machineName', 'Machine Name: ' + formValue.machineName));
    }


    this.loadPageRegisters(0);
  }

我面临的问题是,当用户应用过滤器并打开过滤的寄存器时,如果他单击“后退”按钮再次查看过滤的列表,则应用的过滤器将消失。 vars filterStr(保留URL参数)和filterList(保留应用的过滤器)的值将丢失。

当用户在浏览器中单击“后退”按钮时,如何保存这些值?

2 个答案:

答案 0 :(得分:2)

我的建议是:

  • localStorage:如果您希望过滤器保留更长的时间

    localStorage.setItem('filter', this.filterList.join(',');

  • 角度服务:如果您希望在页面关闭之前拥有过滤器

    constructor(private someService: SomeService) {
        // ...
    
        this.someService.data = this.filterList;
    
        // ...
    }
    

答案 1 :(得分:1)

应用/派生过滤器后,需要将过滤器的值保留为sessionStoragelocalStorage。 使用本机存储API就足够了。

应用初始化时,请检查网络存储中是否有值,并使用存储的值初始化过滤器列表。

您的解决方案将如下所示:

 this.filterList = new Array();

 ngOnInit() {
   const previousFilters = sessionStorage.getItem('FILTER_LIST');
   const filterList = JSON.parse(previousFilters);
   if (filterList) {
     this.filterList = filterList;
   }
 }

 applyFilters(formValue: any) {

    // this.filterList = new Array(); Remove this line since it has been moved to a higher scope

    this.appliedFilters = 0;
    this.filtersStr = '';

    if (formValue.active != null) {
      // ... Do your computations
    }

    if (formValue.idLaboratory != null) {
      // ... Do your computations
    }

    if (formValue.idOwner != null) {
      // ... Do your computations
    }

    if (formValue.machineName != null) {
      // ... Do your computations
    }

    // Then add this bit
    sessionStorage.setItem('FILTER_LIST', JSON.stringify(this.filterList)) 


    this.loadPageRegisters(0);
}

请注意,在此示例中,我正在使用sessionStorage。如果要在关闭浏览器窗口后保留过滤器,请使用localStorage

如果您想要更强大的解决方案,可以看看https://github.com/PillowPillow/ng2-webstorage