How to define several instances of the same ngrx signals store?

Discussão em 'Angular' iniciado por schrödingcöder, Junho 22, 2025.

  1. I've several instances of a component displayed simultaneosly, each having an independent state. I plan to inject a service instance into each of these, with the instance having its own, independent ngrx signals store of the same type.

    How do I define and type those store instanctes?

    Code example:

    import {computed} from '@angular/core';
    import {signalStore, withComputed, withState} from '@ngrx/signals';

    type MessageState = {
    message: string;
    };

    function createMessageStore(initialMessage: string = 'Hello!') {
    return signalStore(
    withState<MessageState>({message: initialMessage}))}

    const MessageStore = createMessageStore()
    type MessageStore = InstanceType<typeof MessageStore>;

    class MessageService {
    constructor(private store: MessageStore) {
    console.log(this.store.message())
    }
    }

    function createMessageService(initialMessage: string = 'Hello!') {
    const store = createMessageStore(initialMessage);
    return new MessageService(store)
    }


    I defined the MessageStore type by following signal store FAQ. However, the line new MessageService(store) gives error TS2345


    Argument of type Type<{ message: (() => string) & { [ɵSIGNAL]: unknown; } & (() => Signal); } & StateSource<{ message: string; }>> is not assignable to parameter of type { message: (() => string) & { [ɵSIGNAL]: unknown; } & (() => Signal); } & StateSource<{ message: string; }>
    ​

    Note that both types appear the same.

    An alternative definition, type MessageStore = ReturnType<typeof createMessageStore> produces, for line console.log(this.store.message()), the error


    TS2339: Property message does not exist on type Type<{ message: (() => string) & { [ɵSIGNAL]: unknown; } & (() => Signal); } & StateSource<{ message: string; }>>
    ​

    How can I correct those errors? Or, what's another way to re-use store instances for identical independent states?

    Continue reading...

Compartilhe esta Página