不重新加载页面的情况下返回Angular应用程序

6

我有一个页面,用户可以通过表单应用一些过滤器,然后用户可以选择一个经过筛选的元素并转到详细页面。

如果用户在详细页面上点击返回按钮,则会被重定向到筛选页面。筛选页面将重新加载,并且不会保留筛选器数据。

我使用history.back()函数来执行返回操作。

我想知道是否有一种方法可以在不重新加载页面的情况下导航回到先前显示的页面,以显示用户在详细链接上单击之前所看到的完全相同的页面。


非副本。 - gh0st
3个回答

8
问题在于,您的筛选页面组件在导航时被销毁,因此组件状态将丢失。您有几个选项来维护筛选状态。 我建议使用localStorage API以序列化方式将状态保存到浏览器中,并在filter-page初始化时检索回来,或者将筛选状态保存到服务中并从那里请求状态。
以下是关于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);
    }
  }
}


2
我正在搜索这个问题的解决方法,最终找到了答案,所以现在发布出来供其他人参考。
我们可以利用 Angular Route Reuse Strategy(Angular路由复用策略)。
请查看下面的链接。

https://medium.com/javascript-in-plain-english/angular-route-reuse-strategy-b5d40adce841#:~:text=When%20navigating%20away%20from%20a,user%2F57%20for%20example)

https://medium.com/@rajeshpillai1996/what-is-routereusestrategy-how-to-cache-components-with-angular-routereusestrategy-82da7790cd2b


0
从一个路由导航到另一个路由将始终销毁当前组件并重新加载下一个组件。在这种情况下,您可以通过ngIf仅从当前组件呈现详细页面。我的意思是基于搜索显示和隐藏两个模板。您不需要更改路由,但这不是首选解决方案。
然而,我更喜欢将数据保存在公共服务中并使用路由策略。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接