Sequential (transactional) API calls in angular 4 with state management

Viewed 1126

I'm looking for some advice to best perform this requirement:

I need to call 3 or 4 separate APIs/endpoints to add a user to our system (using a form).

  • The first call adds a user account and returns an id.
  • The second creates a contact record from a different endpoint using the previous id
  • Then there may be one or two more calls to create other business domain records based on the previous steps.

I have read through a few of the questions concerning multi - sequential requests: Multiple Sequential API calls in Angular 4

But I am wondering how to make the collection of calls perform like a transaction so if any of the steps fail (e.g. email regex in step 2) I can manage the error and also keep track of the step I'm on so I can continue from there as opposed to starting all over again.

I considered a combination of the answer I linked to and localStorage - is there a better solution?

Thanks

1 Answers

In general this can be achieved with concatMap, do and merge operators:

this.formSubmit$
  .concatMap(formData => this.http.post(...).map(user => user.id))
  .do(id => /* save id here */)
  .merge(this.recoverWithId$) // continue from here if you already have an id

  .concatMap(id => this.http.post(...))
  .do(id => /* save whatever you need here */)
  .merge(this.recoverWithWhatever$) // continue from here if already have whatever

  ...
  .retry()
  .subscribe()

If any of the this.http.post emit an error it'll be propagated further and all subsequent steps will be skipped. Also the chain will dispose so that's why I used retry() before subscribe().

You could also use the catch operator but it really depends on what behavior you want to achieve.

Related