@ ngrx / store dispatch从组件工作,但不能从@ngrx / effect工作

时间:2018-02-14 10:23:36

标签: javascript angular ngrx-store ngrx-effects

下面的代码适用于从组件发送时 但是在ngrx / effect

上没有工作(我的意思是更新商店而不是ui)

喜爱-product.reducer.ts ::

case fromFavouriteProduct.ADD_TO_FAVOURITE_PRODUCT_SUCCESS: {
  state.data.push(action.payload);/*working when dispetch from component but not working when dispatch form @effect*/
  // state.data=[] /*but its work always*/
  // state.data=action.payload /*its also  working  always*/
  return {
    ...state,
    loading: false,
    loaded: true,
  }
}

喜爱-product.effect.ts ::

@Effect()
addFavouriteProduct$ = this.actions$.ofType(favouriteProductActions.ADD_TO_FAVOURITE_PRODUCT).pipe(
    switchMap((action: any) => {

        return this.favouriteProductService
            .insert(action.payload)
            .pipe(
                map(result => new favouriteProductActions.AddToFavouriteProductSuccess(result)),
                catchError(error => of(new favouriteProductActions.LoadFavouriteProductFail(error)))
            );

    })
)

2 个答案:

答案 0 :(得分:0)

如果要将输入传递给服务,建议使用map来获取有效负载

@Effect()
addFavouriteProduct$ = this.actions$.ofType(favouriteProductActions.ADD_TO_FAVOURITE_PRODUCT).pipe(
    map((action) => action.payload),
    switchMap((payload) => {

        return this.favouriteProductService
            .insert(payload)
            .pipe(
                map(result => new favouriteProductActions.AddToFavouriteProductSuccess(result)),
                catchError(error => of(new favouriteProductActions.LoadFavouriteProductFail(error)))
            );

答案 1 :(得分:0)

我解决了这个问题 它只是一个愚蠢的:( 虽然状态是不可变对象

 let data = state.data.slice();

        data.push(action.payload);

        return <FavouriteProductState>{
            ...state,
            loading: false,
            loaded: true,
            data

        }