rxMethod on signal store dead after rxjs error

Discussão em 'Angular' iniciado por kerosene, Março 11, 2025.

  1. kerosene

    kerosene Guest

    I'm using a ngrx signal store with rxMethod:

    export const MyStore = signalStore(
    { providedIn: 'root' },
    withState({ loading: false }),
    withMethods((state) => {
    const dataService = inject(DataService);

    return {
    loadMyData: rxMethod<void>(
    pipe(
    tap(() => patchState(state, { loading: true })),
    switchMap(() => dataService.loadDataFromApi()),
    catchError((error) => {
    console.error(error);
    return EMPTY;
    }),
    tap(() => patchState(state, { loading: false }))
    )
    ),
    };
    })
    );



    Now the used DataService throws or might fail:

    @Injectable({
    providedIn: 'root',
    })
    export class DataService {
    loadDataFromApi() {
    return throwError(() => new Error('common data error'));
    }
    }


    I'm using MyStore.loadMyData() on a component

    export class DetailsComponent {
    protected readonly store = inject(MyStore);
    readonly #trigger = signal<void>(undefined);

    constructor() {
    this.store.loadMyData(this.#trigger);
    }
    }


    After the first error occurred on loadMyData the rxMethod does not rerun again. Even if a new DetailsComponent instance if trying to access the in root provided store again.

    I thought that the catchError on the store would have prevented this.

    How can I make sure that my method is still functional even if an error occurs? How is error handling done properly in a rxMethod? Am I doing this the right way?

    See StackBlitz example, where the error is only logged once to the console (no matter how often the details are opened/closed)

    Continue reading...

Compartilhe esta Página