首页 > 解决方案 > 对象 ID 未添加到 ngrx 存储实体

问题描述

我从尝试添加到商店的后期效果操作中获得了一系列帖子。问题是只添加了数组中的第一个 post 对象,并且错误地添加了 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
            });
    }),

标签: angularngrx

解决方案


好吧,事实证明你必须为实体适配器上的 selectId 属性创建一个方法......但是如果你向它添加属性(比如在组实体适配器中),你就不会这样做

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

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

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

推荐阅读