Search code examples
angularsignalsngrxangular-signals

Can a ngrx signal feature store access the state of it's consuming store?


I would like to define a feature store that takes as input(or references) a state from the store which uses/consumes the store, e.g. the parent of the ngrx signal feature store.

For example, I have a store called "withCounters()" that holds a "state variable" called "counterA" of type "number". I would like to add a feature store that can access these state variables.

export function withCounters() {
    withState({
        counterA: 0
    }),

    withDecrement(state)
}

The "withDecrement" feature should be able to access its consumers state, e.g. the "counterA" variable.

 export function withDecrement(consumerState: NgRxParentStore) {
    return signalStoreFeature(

        withMethods((consumerState) => ({

            logState() {
                console.log(consumerState);
            },

            decrement(key: keyof consumerState) {
                patchState(consumerState, {key: consumerState[key]-1});
            }
        }))
    )
}

Is this doable? If yes, how? My main question is how I can access the consumer's store state?


Solution

  • A direct access seems to be not possible without coupling the stores.

    Instead, the ngrx team suggests to use a wrapper function: https://github.com/ngrx/platform/issues/4340

    Read the full thread here:

    A working example with a wrapper function: https://stackblitz.com/edit/ngrx-signal-store-starter-z3q5i5?file=src%2Fmain.ts

    A non working example due to coupling:https://stackblitz.com/edit/ngrx-signal-store-starter-23tsna?file=src%2Fmain.ts