4

I want my app to always do some actions before and after $http running like loading animation or delete all messages.

// Add loading animation + Remove all messages
$http({}).then(function(response) {
    // Remove loading animation + Add Success messages
}, function(response) {
    // Remove loading animation + Add Failure mesages
});

But if I code like this, my code is not DRY. How can I do this without repeat myself?

Thank you!

Andrew Lygin
  • 6,077
  • 1
  • 32
  • 37

2 Answers2

0

You should be able to implement it with Interceptors. Read the below one.

http://www.webdeveasy.com/interceptors-in-angularjs-and-useful-examples/

You can inject your custom service into the Interceptor component. In the request function enable animation ON and turn it OFF in the response function. Your home page should also use the same service to have an animated DIV with an ng-if like

<div ng-if="vm.myHttpStateService.isBusy">
..... animation here ...
</div>
Raghu
  • 699
  • 7
  • 14
-1

Use the promise's .finally method

//Add loading animation + Remove all messages
$http({}).finally(function() {
    //Remove loading animation 
}).then(function onSuccess(response){
    //Add Success messages
}).catch(function onReject(response){
    //Add Failure mesages
});

From the Docs:

The Promise API

Methods

  • finally(callback, notifyCallback) – allows you to observe either the fulfillment or rejection of a promise, but to do so without modifying the final value. This is useful to release resources or do some clean-up that needs to be done whether the promise was rejected or resolved. See the full specification for more information.

-- AngularJS $q Service API Reference -- The Promise API

georgeawg
  • 48,608
  • 13
  • 72
  • 95