我无法从我的实体中删除某项,因为它保存了操作类型

时间:2019-08-27 17:34:19

标签: angular entity adapter store ngrx

我正在处理角度8,并将“收藏夹”添加到我的ngrx Store中,可以添加它们并选择它们,但是我的删除操作失败了,因为(我认为)包括了操作类型在项目上

这是我创建实体和商店简化程序的方式:

export const adapter:EntityAdapter<Favorite>= createEntityAdapter<Favorite>();

export interface FavoriteState extends EntityState<Favorite> {}

export const selectors = adapter.getSelectors();

export class Favorite {
    id: number;
    username: string;
}

然后我创建了动作:

export const addFavoriteAction = createAction('[Favorite] Add Favorite', props<Favorite>());
export const getFavoritesAction = createAction('[Favorite] Get Favorite');
export const removeFavoritesAction = createAction('[Favorite] Delete Favorite', props<Favorite>());

我的reducer非常标准(我正在使用Entity adapter)

// And finally, the reducer
const favoritesReducer = createReducer(initialState,
    on(getFavoritesAction, state => state),
    on(removeFavoritesAction, (state: FavoriteState, favorite: Favorite) => {
        return adapter.removeOne(favorite.username, state);
    }),
    on(addFavoriteAction, (state: FavoriteState, favorite: Favorite) => {
        return adapter.addOne(favorite, state);
    })
);

当我添加收藏夹时,用此:

  addFavorite(username, id) {
    const newFavorite = new Favorite();
    newFavorite.username = username;
    newFavorite.id = id;

    this.favoriteStore.dispatch(addFavoriteAction(newFavorite));
  }

控制台显示我的实体已正确添加,但是我的状态看起来像这样

state: {
entities:
233907: {username: "astaxie", id: 233907, type: "[Favorite] Add Favorite"}
10752102: {username: "libenhe", id: 10752102, type: "[Favorite] Add Favorite"}
20162049: {username: "testerSunshine", id: 20162049, type: "[Favorite] Add Favorite"}
21636478: {username: "TestLeafPages", id: 21636478, type: "[Favorite] Add Favorite"}
ids: (4) [233907, 10752102, 20162049, 21636478]
}

如您所见,状态中包含带有操作字符串的“ type”属性(不确定这是否正确)

因此,当我尝试使用功能删除它时:

 removeFavorite(selected: Favorite) {
    this.favoriteStore.dispatch(removeFavoritesAction(selected));
  }

它发送到减速器的“收藏夹”正在这样输出:

action {
   id: 21636478
   type: "[Favorite] Delete Favorite"
   username: "TestLeafPages"
}

据我了解,适配器的removeOne会尝试在商店的实体数组中找到它,但是由于操作字符串不同,所以找不到它,因此不会将其删除。

我在做什么错了?

1 个答案:

答案 0 :(得分:0)

您将希望像这样更改操作:

export const addFavoriteAction = createAction('[Favorite] Add Favorite', props<{favorite: Favorite}>());

您的减速器是这样的:

on(addFavoriteAction, (state: FavoriteState, { favorite } : { favorite : Favorite }) => {
        return adapter.addOne(favorite, state);
})

最后,要使用您的操作,请向其分发对象:this.favoriteStore.dispatch(addFavoriteAction({ favorite: myFav })