【问题标题】:Angular navigate back without reloading the pageAngular 导航返回而不重新加载页面
【发布时间】:2018-09-21 14:27:20
【问题描述】:

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

如果用户在详细页面上单击返回被重定向到过滤器页面。重新加载过滤器页面,但不保留过滤器数据。

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

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

【问题讨论】:

  • 不是重复的。

标签: angular angular5


【解决方案1】:

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

我建议要么使用 localStorage API 以序列化的方式将状态保存到浏览器,然后在更合适的页面初始化时检索它,或者将过滤器的状态保存到服务中并从那里请求状态。

这是一个非常基本的 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】:
    【解决方案3】:

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

    但是我更喜欢将数据保存在公共服务中并使用路由策略。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-14
      • 2019-06-29
      • 1970-01-01
      • 1970-01-01
      • 2014-06-26
      相关资源
      最近更新 更多