Reputation: 337
I am trying to check for a condition based on which I will either throw an error or continue down to calling an API which shd return a response. I'm not sure how to approach this.
Not very good in rxjs. newbie learning the ropes. Would the following code achieve this? ie in case I dont have a pizza id I would like to fire another error effect else call an API to get the pizzas
getPizzas$ = this.actions$.pipe(
ofType<GetAllPizzas>(PizzaTypes.GetPizzas,
withLatestFrom(
this.store$.pipe(select(fromRootStore.getPizzaId))
),
take(1),
exhaustMap(([customAction, pizzaId]): any => { // << assuming this is correct
if (!pizzaId) {
map(() => new BigProductError({ . /// <<< is this how we approach this? just map? or should we return something?
appmessage : "Boom"
}));
} . /// <<< will control go beyond this point or is this more of an if-else condition?
return this.pizzaService.getPizzas(customAction.orderDetails, pizzaId)
.pipe(
map((pizzas) => new LoadPizzasSuccess(pizzas)),
catchError(error => of(new LoadPizzasFailure(error)))
);
})
);```
Upvotes: 1
Views: 1152
Reputation: 54811
You should throw the BigProductError
error so that subscribers can catch it using catchError()
. Since it is thrown there is no else block required for the if statement.
getPizzas$ = this.actions$.pipe(
ofType<GetAllPizzas>(PizzaTypes.GetPizzas),
withLatestFrom(this.store$.pipe(select(fromRootStore.getPizzaId))),
take(1),
mergeMap(([customAction, pizzaId]) => {
if (!pizzaId) {
throw new BigProductError({appmessage : "Boom"}));
}
return this.pizzaService.getPizzas(customAction.orderDetails, pizzaId)
.pipe(
map((pizzas) => new LoadPizzasSuccess(pizzas)),
catchError(error => of(new LoadPizzasFailure(error)))
);
})
);
I would also use mergeMap()
after the take(1)
because there will only be one value emitted.
Upvotes: 1