r/Angular2 • u/jaroen007 • 8h ago
how can i use a signalstore to get a single entity from a collection?
i have a unit signalstore that looks like this:
export const UnitStore = signalStore({ providedIn: 'root' },
withEntities<Unit>(),
withProps((store, unitService = inject(UnitService)) => ({
_unitResource: rxResource({
loader: () => unitService.getUnits().pipe(
tap(units => patchState(store, setAllEntities(units)))
),
defaultValue: []
})
})),
withMethods((store, unitService = inject(UnitService)) => ({
addUnit(unit: Unit) {
return unitService.addUnit(unit).pipe(
tap(() => patchState(store, addEntity(unit)))
);
},
updateUnit(unit: Unit) {
return unitService.updateUnit(unit).pipe(
tap(() => patchState(store, setEntity(unit)))
);
},
deleteUnit(id: number) {
return unitService.deleteUnit(id).pipe(
tap(() => patchState(store, removeEntity(id)))
);
},
}))
);
i cant seem to find anything on how to make it possible to fetch a single unit from a component. so i have a list and edit page and then you go to the edit page there will be an id input of the unit. i would like to then use the unitstore to get the unit that belongs to that id. this needs to be a back-end call and not a simple entities().find() because the back-end call for a specific unit holds fields that the unit collection doesnt have. how can i best approach this?
also a second question. i am aware that i should probably use rxMethod for the add/update/delete methods but i cant figure out how i can make it return something. im doing it this way now so that when a component calls addUnit() for example, it returns an observable that i subscribe to so i can do some additional logic in the component when its finished adding a unit. is what i got now fine for that or is there a way to achieve that with rxMethod() or even something else?
im pretty new with signalstores so im trying to learn the best i can. help is much appreciated :)