Ricardo
Ricardo

Reputation: 8291

Overiding angularjs function $http.get

I have the following code:

$http.get(url).success(function(response,status,header,config) {
    $scope.mymodel = response;
}

I want to check the http status and call a function. I have to do this change on about 100 http.get calls in whole project. So I want to skip this overriding the success function like this.

function success(response,status,header,config) {
    if(status!=200){
       //my stuff
    }
    super.success(response,status,header,config);
}

Another possibility is replace $http.get(url).success for $http.get(url).success2 in order to tell my mates: "From now on guys use $http.get(url).success2 is cooler!"

Update

I have already know is a deprecated function, I must use it because is a project requirement.

Upvotes: 0

Views: 50

Answers (2)

georgeawg
georgeawg

Reputation: 48968

Deprecation Notice

The $http legacy promise methods success and error have been deprecated. Use the standard then method instead. If $httpProvider.useLegacyPromiseExtensions is set to false then these methods will throw $http/legacy error.

-- AngularJS $http Service API Reference -- Deprecation Notice

Tell your mates: "From now on guys use $http.get(url).then is cooler!"


For other readers:

Response Interceptors

The AngularJS framework provides three places to inject response interceptor functions.

XHR responses can be intercepted and modified globally, locally, or by class.

Upvotes: 0

Charlie
Charlie

Reputation: 23798

You should use $httpProvider.interceptors to achieve this.

You can sniff the $http request and response between to do whatever you want and return the $q unscathed.

$httpProvider.interceptors.push(['$q', 'mathScriptLoadError', function($q, mathScriptLoadError) {
                        return {

                            requestError: function(rejection){                            
                                mathScriptLoadError.anyError(rejection);    
                                return $q.reject(rejection);
                            },

                            responseError: function(rejection){                            
                                mathScriptLoadError.anyError(rejection);
                                return $q.reject(rejection);
                            }
                        };
    }]);

In the above code I get the anyError function of the factory mathScriptLoadError to inspect the rejection and invoke some process based on values. But this doesn't disturb the $http.get at any level.

Upvotes: 1

Related Questions