Skip to content

Instantly share code, notes, and snippets.

@hollygood
Created February 15, 2019 16:36
Show Gist options
  • Save hollygood/e4a5ace951917f6de1e7d22cf671ed05 to your computer and use it in GitHub Desktop.
Save hollygood/e4a5ace951917f6de1e7d22cf671ed05 to your computer and use it in GitHub Desktop.
A more complicated version of multiple http requests by using ngrx store
// Logic order: New User -> (A, B, C) -> D
// Each logic is a single API call to backend
// A, B, C, D services are all depends on the creation of the New User
// A, B, C can be called in any orders, and they don't depends on each other
// After A, B, C all completes, emit D. D shouldn't be called if either A, B or C is not complete
@Effect()
addUser$: Observable<Action> = this.actions$.pipe(
ofType<AddUserAction>(UsersActionType.ADD_USER),
map((action: AddUserAction) => action.payload),
switchMap(payload => {
return this.service.addUser(payload).pipe(
map(res => {
return {
...payload,
user: res
}
}),
switchMap(data => {
let requests = Observable<any>[] = [
of(data.dData), // passing dData to next request
this.aService.addA(data.aData)
];
// adding b, c requests conditionally
if (data.bData) {
requests.push(this.bService.addB(data.bData));
}
if (data.cData) {
requests.push(this.cService.addB(data.cData));
}
return forkJoin(requests);
}),
switchMap(data => {
const [dData, ...rest] = data;
if (condition && dData) {
this.dService.addD(dData).pipe(
map(() => // do something),
catchError(() => // do something)
);
}
}),
catchError(err => {
return of(new Error(err));
});
);
})
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment