On my project with Angular 18 and ngrx I'm trying manage entities with @ngrx/signals
and signalStore.
Suppose that I'm handling the creation of a new entity within the WithMethods method and I'need to know, in the parent component, when the request is complete to change the route, show a tost, etc.
I've done it by passing in the rxMethod
the entity to create and a callback function, but I think there should be a propper way to do it:
export const ToolsStore = signalStore(
{ providedIn: 'root' },
withEntities(entityConfig),
withMethods((store, entityService = inject(entityService)) => ({
createEntity: rxMethod<{ entity: EntityDto; callback: (entity: EntityDto) => void }>(
pipe(
debounceTime(300),
filter((model) => !store.entityIds().includes(model.entity.id!)),
switchMap((model) => {
return entityService.createEntity(model.entity).pipe(
tapResponse({
next: (entity) => {
patchState(store, addEntity(entity, entityConfig));
model.callback(entity);
toast.info('Creating completed!');
},
error: console.error,
}),
);
}),
),
),
})),
);
In the component:
this.toolsStore.createEntity({
entity: entity,
callback: (a) => {
this.router.navigate(['tools', 'entitys', a.id]);
this.createEntity.set(false);
this.entityId.set(a.id || '');
},
});
I saw the watchStore method but I would need more information to understand which entity have been created.
The preferred way would be to have a status property in your state, which the parent component can use to know when the creation is done.
If you have multiple entities that are created at once, that might become a little bit difficult.
The second option would be to do it via a callback, as you have it right now.
So, callback is OK if you can't solve it over metadata in the state.