首页 > 解决方案 > 保持页面状态并导致 Angular 5 与浏览器后退按钮一起使用

问题描述

我有很多与搜索相关的页面。如果单击浏览器后退按钮,我想返回到同一前一页。数据来自 django Rest API。

现在我的解决方案是保存最后调用的 api 并将其保存在会话存储中,但我正在为每个需要这样的东西的新组件编写这么多的会话变量。

有没有一种可管理的方式来处理这样的请求?

标签: angular

解决方案


我认为您正在寻找的是queryParams,因此,如果您基于查询参数构建组件,那么这不仅适用于浏览器的后退按钮,而且还让您可以自由地将 URL 作为链接共享。

阅读下面的查询参数ngOnInit()并构建您的模型。

this._route
    .queryParams
    .subscribe((params) => {
        // based on the received params -> render/request

     })

// here _route is an ActivateRoute instance

编辑

我认为您将不得不收听路由器的更改,很有可能该组件可能不会在导航更改时重新初始化。要处理这个问题,您可以使用类似的东西ngOnInit()

this._router.events
    .filter(event => event instanceof NavigationEnd)
    .subscribe(() => {
         console.log(this._activatedRoute.snapshot.queryParams);
         // get the queryParams here and then based on some conditions, -> render/request, etc
     })

// here _router is a Router instance and _activatedRoute is an ActivatedRoute instance

推荐阅读