Angular:保留组件的状态,但也要重置它



我是Angular的新手,对组件之间的路由有一个需求。该应用程序由3个组件组成:

component_a -> component _b -> component_c

component_b中存在一个列表,该列表可以被过滤和排序。当我从component_b导航到component_c(详细视图)并再次返回(通过浏览器返回)时,应该根据已经输入的值对列表进行过滤和排序。但是,如果我从component_a导航到component_b,过滤器和排序器应该被重置。

过滤器和排序器存储在服务中,因此当从component_c导航回component_b时,它们被读取并再次应用。当从component_a开始时,要重置过滤器/排序器,需要通过路由传递状态,从而触发重置。

component_a

this.router.navigate(["component_b"], {state: {reset: true}});

component_b

if (window.history.state?.reset) {
this.reset();
}

不幸的是,这种行为现在也是这样,当从component_c通过浏览器返回到component_b时,这种状态仍然存在,过滤器/排序器被错误地删除了。我已经尝试过将过滤器/排序器添加到url作为查询参数。但是由于过滤器可能会变得非常复杂,所以这个解决方案对我来说不实用。

我怎样才能正确地实现这个需求?

  1. 如果component_a(当父组件是component_a)component_b,当从导航返回时,component_ccomponent_b,则状态传递给component_a。当component_b时状态丢失正在加载。

State在导航

之前重新加载/加载另一个组件时丢失。如果是这种情况,尝试从component_a再次传递状态

  1. 使用this.router.getCurrentNavigation().extras.state.reset读取状态

    constructor(private router: Router) {
    if(this.router.getCurrentNavigation() !== undefined) {
    if(this.router.getCurrentNavigation().extras !== undefined) {
    if(this.router.getCurrentNavigation().extras.state !== undefined) {
    if(this.router.getCurrentNavigation().extras.state.reset) {
    this.reset();
    }
    }
    }
    }
    }
    

最新更新