I was working on a small project recently. Due to the lack of front-end engineers in the team, I was temporarily asked to write Angular with no experience at all.
I read some basic books and felt that the asynchronous transmission mechanism of rest API in angular is very magical.
At the same time, I am also thinking, if the parameters in your next http request require the get result of the previous request, how to ensure that the parameters can be obtained and not null.
I tried putting the second or third http request after .success, and it was indeed successful, but it felt like the code was very redundant and there were too many nesting levels.
Do you have any suggestions?
The author recommends taking a look at the nested promise and promise chain promise chain
Since Angular’s $http has two built-in shortcut methods, success and error, the standard then method is easy to ignore.
The original poster needs to use promise then nesting
For example
Or use promise chain
Different requirements can use different promise forms
For example, you can also use the Q.all method to complete multiple promises before processing events
Operation in success can ensure that all data is obtained. It is a bit like the chain call of promise.
A piece of code that exists as baseService in a personal project:
The following is the specific postService:
The last thing in blogConroller is probably like this:
If the backend ensures a good REST interface style, it is recommended to use the $resource official plug-in:
You can use it now: