Angular.js code with $ httpProvider and promise. What does it do?

Could you please explain at all what this code does:

App.config(['$httpProvider', function ($httpProvider) {
  $httpProvider.responseInterceptors.push('HttpSpinnerInterceptor');
  $httpProvider.defaults.transformRequest.push(function (data, headersGetter) {
    angular.element('.brand img').attr("src","<%= asset_path('brand/brand.gif') %>");
    return data;
  });
}]);

App.factory('HttpSpinnerInterceptor', function ($q, $window) {
  return function (promise) {
    return promise.then(function (response) {
      angular.element('.brand img').attr("src","<%= asset_path('brand/brand.png') %>");
      return response;
    }, function (response) {
      angular.element('.brand img').attr("src","<%= asset_path('brand/brand.png') %>");
      return $q.reject(response);
    });
  };
});

      

I have absolutely no understanding, apart from some guesses, that it intercepts some kind of response and injects the src attribute of the image.

I don't understand how and when the HttpSpinnerInterceptor is called and what the "promise" parameter is.

+3


source to share


1 answer


  • The HttpSpinnerInterceptor is called after every request issued by the service has $http

    completed (successfully or not), but before the promise has been resolved to the caller (so you can defer the result). Actually the transform request is not needed because it is basically the same as the HttpSpinnerInterceptor (or the HttpSpinnerInterceptor is not needed ...) because it transforms nothing.

  • promise

    the parameter is a promise $q

    that can be used in case you need to perform some asynchronous action when the result of your request is retrieved later, so the caller will receive the result later. In fact, in your code, you directly address this promise (or reject it) by changing the src attribute of the image.

Here are some links to the documentation:



+5


source







All Articles