移动状态后,清除状态会影响其他状态

After moving state, clearing the state affects the other state

我是 ngrx 新手,退订时遇到问题。我正在使用最新版本的 Angular 和 ngrx。

我有 CreateState 和 ModelState。在对话中创建 CreateState 后,我想将 CreateState 复制为 ModelState 的一部分,然后清除 CreateState,使对话变为空。

为此,我首先接收CreateState的整个状态,然后调用ModelState的一个Action进行复制。

this.store$.select(CreateSelectors.selectCreateState).subscribe((state: CreateState.State) => {
  this.store$.dispatch(new ModelActions.CreateAction(state));
  this.router.navigateByUrl('/canvas');
});

移动到新页面后,我正在调用 CreateState 上的操作进行清除。

ngOnInit() {
    this.store$.dispatch(new CreateActions.ClearAction());
}

但我第一页的 Select 订阅似乎仍在监听,因此清除 CreateState 会触发 select 并再次调度 ModelActions.CreateAction.

我尝试只监听 .first() Observable 或取消订阅 Observable 但 Typescript 说 .first().unsubscribe().

没有函数

我是不是弄错了什么?我应该使用不同的方法来移动和清除状态吗?

您从 select 函数订阅了 returns 的可观察对象。 您需要将该可观察对象存储在一个变量中,以便您可以引用它。

然后您可以使用该变量取消订阅

您应该 运行 您的代码通过管道,在那里您可以使用 first() 运算符。

this.store$.select(CreateSelectors.selectCreateState).pipe(
first(), // should unsubscribe after first iteration
tap( (state: CreateState) => {
      this.store$.dispatch(new ModelActions.CreateAction(state));
      this.router.navigateByUrl('/canvas');
})
).subscribe();

或者您可以设置一个变量并订阅它。

const subscription = this.store$.select(CreateSelectors.selectCreateState).pipe(
tap( (state: CreateState) => {
      this.store$.dispatch(new ModelActions.CreateAction(state));
      this.router.navigateByUrl('/canvas');
})
);

// if you don't subscribe nothing will happen
// unsubscribes after first iteration
subscription.first().subscribe(); 

一些文档:

first()

现场演示

first() 的文档RxJS Documentation learn-rxjs