How can I call a method inside another signal store method

Discussão em 'Angular' iniciado por Johannes Schacht, Janeiro 9, 2025.

  1. I have a signal store with method loadItems() and a method countItems(). loadItems should call countItemsat the end of its operation. How is that possible? Is that possible at all. And would that also work with rxMethods?

    stackblitz: https://stackblitz.com/edit/stackbl.../main.ts,package.json,src/app/sample-store.ts

    This is the store:

    export const sampleStore = signalStore(
    { providedIn: 'root' },

    withState({
    items: [] as string[],
    itemCount: 0,
    }),

    withMethods((store) => ({
    loadItems: () => {
    patchState(store, { items: ['one', 'tow', 'three'] });
    // countItems(); // Not possible
    },
    countItems: () => {
    patchState(store, { itemCount: store.items().length });
    },
    }))
    );


    And this is the component:

    @Component({
    selector: 'app-root',
    standalone: true,
    template: `
    <div>Items: {{sampleStore.items()}}</div>
    <div>ItemCount: {{sampleStore.itemCount()}}</div>
    `,
    })
    export class App implements OnInit {
    sampleStore = inject(sampleStore);

    ngOnInit(): void {
    this.sampleStore.loadItems();
    // this.sampleStore.countItems();
    }
    }

    bootstrapApplication(App);


    If you un-comment this.sampleStore.countItems(); the expected happens. But I would like to call countItems() at the end of loadItems().

    Continue reading...

Compartilhe esta Página