Angular 在不重新加载页面的情况下返回

Angular navigate back without reloading the page

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

如果用户在详细信息页面上点击后退,则会被重定向到筛选页面。重新加载过滤器页面而不保留过滤器数据。

我使用 history.back() 函数进行后退操作。

我想知道是否有一种方法可以在不重新加载页面的情况下导航回页面,显示在用户单击详细信息之前显示的确切页面 link。

问题是,您的过滤页面组件在导航时被破坏,因此组件状态将丢失。您有几个选项来维护过滤器状态。

我建议要么使用 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);
    }
  }
}

从一条路线导航到另一条路线总是会销毁当前组件并重新加载下一个组件。在这种情况下,您只能通过 ngIf 从当前组件呈现详细信息页面。我的意思是根据搜索显示和隐藏这两个模板。您不需要更改路线,但这不是首选解决方案。

不过我更愿意在公共服务中保存数据并使用路由策略。

我正在搜索这个,找到了解决方案,所以将其发布给其他人。

我们可以利用Angular Route Reuse Strategy.

检查以下链接

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