How can I insert commands before or prevent $http's JSONP automatic parsing in AngularJS?

荒凉一梦 提交于 2019-12-04 22:57:32

This has been tested and does work. Let me know if you have any further questions. http://jsfiddle.net/moderndegree/Kn3Tc/

HTML

<div ng-app="myApp">
    <div ng-controller="myController">
        {{results.tada}}
    </div>
</div>

Javascript

angular.module('myApp', ['ngResource']).
factory('myService', function($http, $resource, $log){
    return $resource('/', {}, {
        get: {
            method: 'GET',
            // placed custom transform ahead of $http default
            transformRequest: [function(data, headersGetter){
                $log.info(data);
                $log.info(headersGetter());
            }].concat($http.defaults.transformRequest),
            // placed custom transform ahead of $http default
            transformResponse: [function (data, headersGetter) {
                $log.info(data);
                $log.info(headersGetter());
                data = {tada:"Check your console"};
                return data;
            }].concat($http.defaults.transformResponse)
        }
    });
}).
controller('myController', function(myService, $scope) {
    $scope.results = myService.get();
});

Update To use JSONP, just switch the method to JSONP. You can read more about ngResource here.

Here is what the angular documentation says

To globally augment or override the default transforms, modify the $httpProvider.defaults.transformRequest and $httpProvider.defaults.transformResponse properties. These properties are by default an array of transform functions, which allows you to push or unshift a new transformation function into the transformation chain. You can also decide to completely override any default transformations by assigning your transformation functions to these properties directly without the array wrapper.

Basically what you would need to do is to configure the $httpProvider

angular.module('myApp', [])
    .config(['$httpProvider', function ($httpProvider) {
//Define your transform function
//push your trasform function to the start of the array  $httpProvider.defaults.transformResponse
//Or replace the transformResponse array with a function or a new array of tranform functions.

}]);

Now the trasform function that you implement should be first function in the array. Since there is already a string to JSON transform function there.

Angular has added $jsonpCallbacks in version 1.5.8 https://github.com/angular/angular.js/blob/master/src/ng/jsonpCallbacks.js

This allows you to modify the callback function.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!