angularngrxngrx-storeangular-signals

How can I call a method inside another signal store method


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/stackblitz-starters-b9xpmc?file=src%2Findex.html,src%2Fmain.ts,package.json,src%2Fapp%2Fsample-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().


Solution

  • Yes it is possible, just change your code to the following

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