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

时间:2018-10-09 12:09:50

标签: angular ngrx angular-redux

我是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 Subscription仍在侦听,因此清除CreateState会触发选择并再次分派ModelActions.CreateAction。

我尝试仅监听.first()或从Observable取消订阅,但是打字稿说.first().unsubscribe()没有任何功能。

我弄错了吗?我应该使用其他方法移动和清除状态吗?

2 个答案:

答案 0 :(得分:3)

您应该通过管道运行代码,您可以在其中使用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

的文档

答案 1 :(得分:0)

您订阅了从选择函数返回的可观察对象。 您需要将可观察值存储在变量中,以便可以引用它。

然后您可以使用该变量退订

相关问题