I writing app, that i can save events in mongodb by using ngxs where I injected serverService. When I'm sending event I do that without id ,because mongo adding id automatically, just wait for it and then patch state. (insertEvent returng id then I look for whole Event and fetch that)
@Action(CreateEvent)
createEvent({ getState, patchState }: StateContext<EventStateModel>, { event }: CreateEvent) {
this.eventsService.insertEvent(event)
.pipe(map(id => id['id']))
.pipe(switchMap(id => id ? this.eventsService.getEventById(id) : empty() ))
.subscribe(event => {
const { events } = getState();
patchState({
events: [
...events,
event
]
});
});
}
But after add event I want to get this Id, to direct to event view. I don't know how to get event with id.
createRandom(){
this.store.dispatch(
new CreateEvent(EventFactory.create())
)
}
When I'm try to use action handling ,it always returns me event with mock id by me.
this.actions$.pipe(ofActionSuccessful(CreateEvent)).subscribe((ev) => {
console.log(ev)
})
Yes, the action stream in this case will return the the payload of the action you dispatched (with the mock ID).
I can see two options here:
EventCreated
that you can then subscribe to - and in this action payload, include the details (the ID) of what was just created. Dispatch it after your patch
operation.or
withLatestFrom
operator to grab the latest view of the state, and inspect the last event
in your `events array to see what ID was generated.