对象ID未添加到ngrx存储实体

时间:2020-06-25 17:06:45

标签: angular ngrx

我从尝试添加到商店的后期效果操作中获取了一系列帖子。问题在于,仅添加了数组中的第一个post对象,因此错误地添加了id(因为id丢失了(它从后端作为_id返回,但是我对组实体使用了相同的设置,并且工作正常, id是根据the_id属性自动添加的)。 任何帮助将不胜感激。

后期效果:

getGroupPosts$ = createEffect(() =>
        this.actions$.pipe(
            ofType(PostActions.getGroupPosts),
            switchMap(action => {
                return this.http
                    .get<{ posts: Post[] }>
                    (`${BACKEND_URL}/posts/${action.groupId}?pageSize=${action.pageSize}&currentPage=${action.pageNumber}`)
                    .pipe(
                        map(response => {
                            this.store.dispatch(GroupActions.groupPostsLoaded({ groupId: action.groupId }));
                            return {
                                type: PostActions.GET_GROUP_POSTS_SUCCESS,
                                posts: response.posts
                            };
                        }),
                        catchError(err => this.handleError(err, PostActions.GET_GROUP_POSTS_FAILED))
                    );
            })
        )
    );

    getGroupPostsSucess$ = createEffect(() =>
        this.actions$
            .pipe(
                ofType(PostActions.getGroupPostsSuccess),
                map(action => {
                    return {
                        type: SpinnerActions.STOP_SPINNER
                    };
                })
            )
    );

后减速器:

import { EntityState, createEntityAdapter } from '@ngrx/entity';
import { Post } from 'src/app/models/post.model';
import { createReducer, on } from '@ngrx/store';
import * as PostActions from './post.actions';

export interface PostState extends EntityState<Post> { }

export const adapter = createEntityAdapter<Post>();

export const initPostsState = adapter.getInitialState();

export const postReducer = createReducer(
    initPostsState,
    on(PostActions.createPostSuccess, (state, action) => {
        return adapter.addOne(action.post, { ...state });
    }),
    on(PostActions.getGroupPostsSuccess, (state, action) => {
        console.log(action);

        return adapter.addMany(action.posts, { ...state });
    })
);

export const {
    selectAll,
} = adapter.getSelectors();

小组效应:

getTopicGroups$ = createEffect(() =>
    this.actions$
        .pipe(
            ofType(GroupActions.getTopicGroups),
            switchMap(action => {
                this.topic = action.topic;
                return this.http
                    .get<{ groups: Group[], count: number }>(
                        `${BACKEND_URL}/groups/${this.topic}?pageNumber=${action.pageNumber}&pageSize=${action.pageSize}`)
                    .pipe(
                        map(response => {
                            return {
                                type: GroupActions.GET_TOPIC_GROUPS_SUCCESS,
                                groups: response.groups,
                                topic: this.topic,
                                count: response.count,
                                groupsLoaded: response.groups.length
                            };
                        }),
                        catchError(err => this.handleError(err, GroupActions.GET_TOPIC_GROUPS_FAILED))
                    );
            })
        )
);

getTopicGroupSuccess$ = createEffect(() =>
    this.actions$
        .pipe(
            ofType(GroupActions.getTopicGroupsSuccess),
            map(action => {
                return {
                    type: SpinnerActions.STOP_SPINNER
                };
            })
        )
);

组减速器:

export interface GroupState extends EntityState<Group> {
    topicsLoaded: {
        topic: string,
        count: number,
        groupsLoaded: number
    }[];
}

export const adapter = createEntityAdapter<Group>();

export const initialGroupState = adapter.getInitialState({
    topicsLoaded: []
});

export const groupReducer = createReducer(
    initialGroupState,
    on(GroupActions.getTopicGroupsSuccess, (state, action) => {
        let oldTopics;
        let newTopics;
        // Check if 1st batch of groups have already been loaded //
        const oldGroupsLoaded = state.topicsLoaded.find(g => g.topic === action.topic);

        if (!oldGroupsLoaded) {
            // Add topic to group entity //
            newTopics = [...state.topicsLoaded];
            newTopics.push({
                topic: action.topic,
                count: action.count,
                groupsLoaded: action.groupsLoaded
            });
        } else {
            // Update group entity //
            const index = [...state.topicsLoaded].indexOf(oldGroupsLoaded);
            oldTopics = [...state.topicsLoaded];
            oldTopics[index] = {
                ...state.topicsLoaded[index],
                groupsLoaded: state.topicsLoaded[index].groupsLoaded + action.groupsLoaded
            };
        }
        return adapter.addMany(action.groups,
            {
                ...state,
                topicsLoaded: oldGroupsLoaded ? oldTopics : newTopics
            });
    }),

1 个答案:

答案 0 :(得分:0)

好吧,事实证明您必须在实体适配器上为selectId属性创建一个方法...但是,如果您向其添加属性(例如在组实体适配器中),则不知道如何

export interface PostState extends EntityState<Post> {
    selectPostId: string;
}

export const selectPostId = (post: Post) => post._id;

export const adapter = createEntityAdapter<Post>({
    selectId: selectPostId
});