Ngrx Signal Store Multiple states

Discussão em 'Angular' iniciado por Zed, Novembro 15, 2024.

  1. Zed

    Zed Guest

    Problem Description


    I have a store that retrieves the data of the connected user. However, the user can have different roles, such as admin, user, or moderator. Each role has its own model that inherits from the base User model.

    I have multiple methods, such as LoadCurrentAdmin, LoadCurrentModo, or LoadCurrentUser. What I did is create a store with this state:

    export interface LoadUserState {
    user: User | undefined | null;
    admin: Admin | undefined | null;
    modo: Modo | undefined | null;
    isLoading: boolean;
    }

    const initialValue: LoadUserState = {
    user: undefined,
    admin: undefined,
    Modo: undefined,
    isLoading: false,
    };


    In withMethods, I created several methods, such as:

    withMethods(
    (store, infra = inject(UserInfrastructure), router = inject(Router)) => ({
    getCurrentAdmin: rxMethod<string>(
    pipe(
    tap(() => patchState(store, { isLoading: true })),
    concatMap((input) => {
    return infra.loadCurrentAdmin(input).pipe(
    tapResponse({
    next: (admin) => {
    patchState(store, {
    isLoading: false,
    admin: admin,
    });
    },
    error: () => {
    patchState(store, { isLoading: false });
    },
    })
    );
    })
    )
    ),
    getCurrentModo: rxMethod<string>(
    pipe(
    tap(() => patchState(store, { isLoading: true })),
    concatMap((input) => {
    return infra.loadCurrentModo(input).pipe(
    tapResponse({
    next: (sdr) => {
    patchState(store, {
    isLoading: false,
    modo: modo,
    });
    },
    error: () => {
    patchState(store, { isLoading: false });
    },
    })
    );
    })
    )
    ),


    My question is: should I create a separate store for each role, or can I do it the way I did, for example, by having a state for both modo and admin? Depending on the role, I load the admin and leave the modo as undefined.

    Continue reading...

Compartilhe esta Página