Reputation: 987
I'm having trouble understanding the best way to work with and handle data from a backend api in an angular2+ service.
For example when creating a cart system. I initially send a get
request to the backend to get the current cart. This is where I start having difficulties, when it comes to working with this data.
What is the best way to update the data? If the method to update the data just involves sending a put/post request to the backend - my components that are subscribed to the data would not be updated. If I include in that logic another get
request to get the updated data, theres a chance that the get request will return before my backend logic is able to update the value to the db and return the updated value. There are other options available to me, like using Subjects
, but those too have their issues.
This seems like an obvious and common task so I'm not sure if there's something obvious that I'm missing.
If you were to create a cart system, or a like system, or anything that gets an initial value from a backend and needs to be updated, how would you handle that data - what would be your workflow?
Upvotes: 0
Views: 60
Reputation: 2701
Don't see this as the best way but just a way:
Getting the data is done on some user action - e.g. entering a page or pressing the refresh button. Doing so will allow the end user to view/interact with data.
When updating data, send data to the server and if it returns a success response (and it should respond in some way that the operation is acknowledged on the server side) then treat the current client data as the current state of that data, so no additional get request. On error response or timeout handle as needed.
If there is a need from the server to update or change the sent data, then the server could send that change in the response to the update request (Id for example) or it could send some information about when it will be possible to get the correct state of the data (timespan for example).
If there is a possibility that some other source will edit the data on the server and that happens after you received the old data but before you update it, then you could return an error response that will warn the user that the data is changed and it needs to be refreshed (manually or by user clicking the OK button on the warning) after which you send a get request to the server again.
It could be seen as bad user experience if the user updates some data and is presented with data that is changed on some other source and not with the edits he made.
Upvotes: 1