j3r6me
j3r6me

Reputation: 808

Routing with http calls in Angular 2

I am looking for the best way to route between my components in Angular 2. In my application I go from page to page by submitting a form:

At each step the backend can return an error and we either go back to previous page, or display an error page (fatal error).

I see two simple options to do the ajax call:

  1. Component A only displays the form and forward the input parameters to component B. Component B run the ajax call and display the result.
  2. OR component A run the ajax call with the input parameters he has and forward the result to component B for display. In case of error component A redisplay itself.

The problem with option 1 is that in case of error the backend will respond with the page A business model and an error message. Component B will have to forward the result to component A so page A can be redisplayed.

The problem with option 2 is that component A has part of the business logic of component B which is not really good for component encapsulation.

My question is: is there a good design pattern to do this? Should I use an intermediate component for example?

Thank you for your help.

Upvotes: 0

Views: 259

Answers (1)

Sasxa
Sasxa

Reputation: 41264

I would move all ajax calls to parent component and keep all the data there too, assuming forms are independent. So workflow would be like this:

  1. cP(arent) go to cA

  2. cA - show form, send data to cP

  3. cP - send A data via ajax, go to cB

  4. cB - show form, send data to cP

  5. cP - (got error for A data), send B data via ajax, go to cC

  6. cC - show form, notify user there was an error with form A, offer user to go back now, or finish step C and do A later, send data to cP

  7. cP - (got fatal error for B data), don't send C data via ajax, save data to localStorage?, tell user to try later...

    ...etc. It's more user friendly and you can show pages/forms as needed.

If forms depend on each other, I'd still keep the ajax and data in parent, and display them if/when server responds. But I recommend you design them do be independent, or you can play some elevator music while user waits (;

Upvotes: 2

Related Questions