Angular Service JSONP Request with Custom Callback

梦想与她 提交于 2019-12-25 03:42:05

问题


I'm pulling from JSONP feeds that have custom callback functions, for example:

jsonpCallbackAllStar2015({
    "events": [
        {
            "title": "XYZ"
        }
        ...
    ]
})

I'm able to do this, using the solution posted here like so:

var jsonUrl = 'http://i.cdn.turner.com/nba/nba/.element/media/2.0/teamsites/warriors/json/json-as2015.js?callback=JSON_CALLBACK' + (new Date().getTime());

$http.jsonp(jsonUrl);

window.jsonpCallbackAllStar2015 = function(data) {
    $scope.events = data.events;
}

However I would now like to do this in a service so that I can load the data one time and inject it into all of my controllers. When I try this, however, I get an $injector undefined error, which I'm guessing is because the service doesn't return fast enough:

eventsFactory.$inject = ['$http'];
function eventsFactory($http) {
    var jsonUrl = 'http://i.cdn.turner.com/nba/nba/.element/media/2.0/teamsites/warriors/json/json-as2015.js?callback=JSON_CALLBACK' + (new Date().getTime());

    $http.jsonp(jsonUrl);

    window.jsonpCallbackAllStar2015 = function(data) {
        return data.events;
    }
}

Is there anyway to fix this or will I have to repeat the jsonp request in each controller? Here is a fiddle.


回答1:


While it's not a beautiful solution this should work for you. I added in some very basic caching. I haven't used jsonp in angular and it seems that setting the cache in the $http config doesn't work. It would have been a better option.

app.factory('eventsFactory', [ '$http', '$q', 
    function( $http, $q ) {

        var pub = {};

        var jsonUrl = 'http://i.cdn.turner.com/nba/nba/.element/media/2.0/teamsites/warriors/json/json-as2015.js?callback=JSON_CALLBACK' + (new Date().getTime()),
            cachedResponse;

        pub.getEvent = function() {

            var deferred = $q.defer();

            if ( cachedResponse ) {
                deferred.resolve( cachedResponse );
            }

            else {

                $http.jsonp( jsonUrl );

                window.jsonpCallbackAllStar2015 = function( data ) {
                    cachedResponse = data;
                    deferred.resolve( data );
                }

            }

            return deferred.promise;

        };

        return pub;

    }
]);

Now inside of your controller you can do this:

app.controller('someController', [ 'eventsFactory', 
    function( eventsFactory) {

        eventsFactory.getEvent().then(function( data ) {
            console.log( data );
        });

    }
]);


来源:https://stackoverflow.com/questions/28755469/angular-service-jsonp-request-with-custom-callback

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