Angular向后导航而无需重新加载页面

Ker*_*y82 2 angular angular5

我有一个页面,用户可以在该页面上应用一些过滤器(通过表单),然后用户可以选择过滤的元素之一并转到详细信息页面。

如果用户在详细信息页面上单击返回,则会被重定向到过滤器页面。在不保留过滤器数据的情况下重新加载了过滤器页面。

我将history.back()函数用于后退动作。

我想知道是否存在一种导航到页面的方法,而无需重新加载该页面即可显示用户单击详细信息链接之前显示的确切页面。

Pet*_*ger 5

问题是,您的筛选器页面组件在导航时被破坏,因此组件状态将丢失。您可以使用服务器选项来维护过滤器状态。

我建议您使用localStorage API以串行化的方式将状态保存到浏览器,然后在fiter-page init上将其取回,或者将过滤器的状态保存到服务中并从那里请求状态。

这是localStorage的一个非常基本的示例。(不确定代码是否完全有效,但是您应该明白这一点。)

export class FilterPage implements OnInit, OnDestroy {

  private filterItems: string[];

  constructor() { }

  ngOnInit() {
    if (localStorage.getItem('filterItems'))
      this.filterItems = JSON.parse(localStorage.getItem('filterItems'));
    } else {
      this.filterItems = [];
    }
  }
  
  ngOnDestroy() {
    if(this.filterItems.length > 0) {
      localStorage.setItem('filterItems', JSON.stringify(this.filterItems));
    }
  }
  
  addFilterItem(item: string) {
    if (!this.filterItems.includes(item)) {
      this.filterItems = [...this.filterItems, item];
    }
  }
  
  removeFilterItem(item: string) {
    if (this.filterItems.includes(item)) {
      this.filterItems = this.fiterItems.filter(currentItem => currentItem !== item);
    }
  }
}
Run Code Online (Sandbox Code Playgroud)