小编Ein*_*rzt的帖子

使用 NGXS 订阅操作流的更简洁方式

所以我通常有一种在点击时调度操作的方法:

create() {
  this.store.dispatch(new Create(this.form.value)); 
}
Run Code Online (Sandbox Code Playgroud)

此代码触发以下场景,并根据请求是否失败调度 CreateSuccess 或 CreateFailed

@Action(Create)
create({ dispatch }: StateContext<StateInterface>, { entity}: Create) {
  return this.http.post('mybackend', entity).pipe(
    tap<EntityType>(resp => dispatch(new CreateSuccess(resp))),
    catchError(error => dispatch(new CreateFailed(error)))
  ); 
}
Run Code Online (Sandbox Code Playgroud)

现在,在我调用的组件内,create()我正在监听这两个操作。

this.actions$.pipe(
  ofActionSuccessful(CreateSuccess, UpdateSuccess),
  takeUntil(componentDestroyed(this)) // <--
).subscribe(action => doStuff());
Run Code Online (Sandbox Code Playgroud)

这一切都完美地工作,唯一困扰我的是每次我使用它时,我都必须添加 takeUntil() 部分,以便在组件被销毁时取消订阅。

我知道这对每个人来说可能不是一个真正的问题,但我想知道是否有更干净的方法来做到这一点。

我考虑过一个自定义的 RxJS 运算符可以处理这个问题,但也许还有其他选项,或者(我还没有找到任何相关内容),NGXS 有没有办法自行取消订阅?

redux angular ngxs

7
推荐指数
1
解决办法
8405
查看次数

标签 统计

angular ×1

ngxs ×1

redux ×1