【问题标题】:Maintain form values ​when redirecting and going back in the browser, in angular在浏览器中重定向和返回时保持表单值,角度
【发布时间】:2019-07-12 18:39:46
【问题描述】:

在我执行搜索的程序中,完成了一个表单(使用响应式表单),提交时,使用过滤器创建一个 json 并重定向到另一个页面,将过滤器作为参数发送。在另一个页面上,使用了一个休息服务来最终显示结果。

当用户单击浏览器的“后退”按钮时会出现问题。返回上一页时,表单中不维护过滤器。有一些方法可以确保这些过滤器得到维护

【问题讨论】:

    标签: angular


    【解决方案1】:

    路由器参数如何?它使您的页面可添加书签,并且对后退和前进浏览器按钮很友好。

    http://localhost:4200/filter?input1=someData&input2=anotherData

    当您发送表单时,您还可以使用参数重定向到同一页面。

    Here is a nice article about it

    因此,如果您的用户单击“返回”一次,他们将进入带有过滤器的搜索表单。如果他们再次点击“返回”,他们将处于空白表单中。


    如果您不想使用路由器参数,可以将数据保存在localStoragesessionStorage 并重新填充过滤器ngOnInit

    export class Something implements OnInit {
    
       ngOnInit() {
    
          if(localStorage.getItem('search') !== undefined) {
             const filters = JSON.parse(localStorage.getItem('search'));
             // Do someting with it
          }
       }
    
       search(searchParams) {
    
          // Save your filters before redirect
          localStorage.setItem('search', JSON.stringify(searchParams));
    
          // Your code
       }
    }
    
    

    【讨论】:

    • 这不是我所需要的,但它们是好主意。 localstorage 的选项可能是一个解决方案,但有必要添加更多逻辑以避免在想要进行新搜索时它不显示以前的过滤器。无论如何感谢您的回答
    【解决方案2】:

    按照 Haytam95 的建议,使用参数(而不是 queryParams)。 但是我没有重定向到同一页面,而是进行了两次重定向。首先我使用replaceURL 来替换空表单。这样当我返回时,我会得到带有最后一个过滤器的表单。

    this.router.navigate([],
          {
            queryParams: {filters: btoa(JSON.stringify(filter)), page: 0 },
            relativeTo: this.activatedRoute,
            queryParamsHandling: 'merge',
            replaceUrl: true
           }).then(
            () => {
              this.router.navigate(['/pages/fallos/list'], { queryParams: {filters: btoa(JSON.stringify(filter)), page: 0 } });
            }
           );
    

    【讨论】:

      猜你喜欢
      • 2015-06-14
      • 2019-01-31
      • 1970-01-01
      • 2015-05-01
      • 1970-01-01
      • 2012-08-26
      • 2021-12-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多