5

我从一个效果返回多个动作, concatMap 按顺序发送动作,但不要等待完成发送下一个动作。loadDetails 在收到 loadDetailsS​​uccess 时调用 REST 服务并更新存储

我想在调用 HttpResultActions.httpRequestUpdateSuccessful() 之前完成 loadDetailsAction。

怎样才能做到这一点?来自不同的动作?

@Effect()
  removeLibelle$ = this.actions$
    .ofType(DetailsActions.DELETE_LIBELLE)
    .map(toPayload)
    .withLatestFrom(this.store$.select(state => state.tree))
    .switchMap(([payload, tree]) => this.libelleService.deleteItem(payload)
      .concatMap(() => {
        return [
         DetailsActions.clear(), //function dispatch action clear
          DetailsActions.loadDetails({ entity: tree.entity,
            dateSearch: tree.search.dateSearch }), //function dispatch GET
          HttpResultActions.httpRequestUpdateSuccessful() //Dispatch action to show modal success
        ];
      }).catch(error => Observable.of(HttpResultActions.httpRequestError(error))));
4

1 回答 1

5

您在单一效果中做了太多事情。您可以随意将其分解为多种效果。这样想。

DELETE ---> perform delete ----> DELETE_SUCCESS , DELETE_ERROR

DELETE_SUCCESS ---> clear data ----> DATA_CLEAR_SUCCESS

DATA_CLEAR_SUCCESS ----> load data ----> LOAD_DATA_SUCCESS 

我做了一系列的动作。您也可以并行执行它们。可能您想立即触发清除数据和加载数据,然后它看起来像这样:

DELETE ---> perform delete ----> DELETE_SUCCESS , DELETE_ERROR

DELETE_SUCCESS ---> clear data ----> DATA_CLEAR_SUCCESS

DELETE_SUCCESS ----> load data ----> LOAD_DATA_SUCCESS 

现在,您可以在任何这些操作中执行模型更改。有趣的部分是,你可能有相同的模型更改获取 http 调用或删除成功后获取 http 调用。这就是 redux 的美妙之处。

您的代码如下所示

@Effect()
  removeLibelle$ = this.actions$
    .ofType(DetailsActions.DELETE_LIBELLE)
    .map(toPayload)
    .withLatestFrom(this.store$.select(state => state.tree))
    .switchMap(([payload, tree]) => 
        this.libelleService.deleteItem(payload)
    )// return DELETE_SUCCESS
    .catch() //return DELETE_FAIL

 @Effect()
  removeLibelleDataClear$ = this.actions$
    .ofType(DetailsActions.DELETE_LIBELLE)
        //perform  DetailsActions.clear(),
        //return DATA_CLEAR_SUCCESS action
        // return DATA_CLEAR_ERROR action 

 // If you want to data load in parallell with clear, 
 // you can listen on delete_success . If you want to do 
 // it after data_clear, then listen on data_clear_success 
 @Effect()
  removeLibelleDataClear$ = this.actions$
    .ofType(DetailsActions.DATA_CLEAR_SUCCESS)
        //perform  
        //DetailsActions.loadDetails({ entity: tree.entity,
        //    dateSearch: tree.search.dateSearch })
        // DATA_LOAD_SUCCESS 
        //catch: DATA_LOAD_ERROR

您可能希望立即通知用户删除成功。并刷新数据。或者您可以添加不同的操作 DELETE_SUCCESS_DATA_LOAD_SUCCESS 并通知用户删除成功。

打破这种方式使测试变得非常容易,将其与复杂的 switchmap+concat+三个 http 调用进行比较。

于 2017-06-15T02:01:54.647 回答