Requirements: Angular projects, when clicking a button on a page, will send an HTTP request, because some interfaces are time-consuming, need to display the loading animation effect, when the HTTP request is completed, the loading animation will be closed.When the request is successful or an error occurs, you need to turn off the loading animation。
Conventional writing
As follows:
That is, when the request succeeds and an error occurs, you need to call the close loading animation, is there an easier way? Similar to try-catch-finally in C#.
Use the finalize operator
What it does is try-catch-finalfinallyfunction, we only need to write the code once, and the logic will be executed regardless of success or failure.
The code is as follows:
How does finalize work? It basically adds a callback add(fn) to the disassembly of an observable object by subscribing. This guarantees that it will be called on error, completion, and unsubscription.
Note that the finalize operator is executed as soon as our Observable is terminated. This is important! For Angular HTTP, this works very well because the Angular HTTP service returns "done" once the request is complete.
(End) |