Search code examples
javascriptangularjsjsonp

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


It seems like pretty much every question or explanation I find regarding $http or angularjs in general assumes you can modify the response from your requests. I can't do that and the response I'm getting is malformed (according to the AngularJS parser). It's malformed in a consistent way so I could modify the plain text to fix the problem before parsing it, but both response interceptors and transform response functions occur after the default (content type based?) parsing.

Edit: The issue is with the fact that I need to use the JSONP methodology to make a request for information from another site, but the data does not have the expected JSONP callback so something (I'm still not sure if its the browser based on the content or the AngularJS code) throws a syntax error.

New question: Does anyone know a way around this?


Solution

  • 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.