【问题标题】:ngrx - how to perform an operation once a dispatched action has successfully updated the store?ngrx - 一旦分派的操作成功更新了商店,如何执行操作?
【发布时间】:2017-10-04 08:37:52
【问题描述】:

我正在尝试在我使用 @ngrx/store 的 Angular 应用程序中实现撤消操作。我想要做的是调度 UNDO 动作,然后一旦动作被处理,数据已经被 reducer 更新并被推送到 store,我想对更新的数据做一些事情。

这就是我目前正在尝试解决的问题。基本上,因为 records$ 来自 BehaviorSubject,所以我最初会在订阅时获得一个值。然后我发送操作并等待更新通过。必须有更好的方法,对吧?

undoRecords() {
    let count = 1;
    // The records$ observable comes from the ngrx store
    let obs = this.records$.take(2).subscribe(records => {
        if(count == 1) {
            this.store.dispatch({type: UNDO_RECORDS, payload: undefined}); // this will change the records 
            count++;
        }
        else {
            this.someService.doSomething(records);
        }
    });
}

【问题讨论】:

    标签: javascript angular redux rxjs ngrx


    【解决方案1】:

    我通常做的是三个动作: 行动,行动成功,行动错误。

    如果您有兴趣跟踪进度,ACTION 会触发实际操作以及更改存储中的状态 (inprogress=true)。

    ACTION_SUCCESS ,将状态“进行中”设置为假。并更新实际数据。

    您可以监控正在进行的状态,并且您将知道任务何时完成。

    【讨论】:

      【解决方案2】:

      使用 npm 包 ngrx-undo。

       npm install --save ngrx-undo
      

      在您的 AppModule 中:

      import {handleUndo, configureBufferSize} from 'ngrx-undo';
      
      // if you want to update the buffer (which defaults to 100)
      configureBufferSize(150);
      
      @NgModule({
          imports: [
              // pass the handleUndo in the metaReducers
              StoreModule.provideStore(rootReducer, {metaReducers: [handleUndo]}) 
          ]
      })
      export class AppModule { }
      

      要撤消操作,只需使用撤消操作创建器。

      import {undo} from "ngrx-undo";
      
      // create an action
      let action = {type: REMOVE_WINE, payload: {id: wine.id}};
      
      // dispatch it
      this.store.dispatch(action);
      
      // undo the action
      this.store.dispatch(undo(action));
      

      看看here

      【讨论】:

      • 感谢@George 的回复。澄清一下,我已经能够成功实现撤消功能(尽管不是您发布的库)。我的意思是,撤消操作成功后,我想对撤消操作的结果数据做一些事情。有什么想法吗?
      猜你喜欢
      • 2018-10-24
      • 1970-01-01
      • 1970-01-01
      • 2019-08-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-11
      • 1970-01-01
      相关资源
      最近更新 更多