代码之家  ›  专栏  ›  技术社区  ›  dougmacklin

带有自定义回调的Angular Service JSONP请求

  •  0
  • dougmacklin  · 技术社区  · 10 年前

    我从具有自定义回调函数的JSONP提要中提取, for example :

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

    我可以使用 solution posted here 像这样:

    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;
    }
    

    然而,我现在想在服务中这样做,这样我就可以一次性加载数据并将其注入到所有控制器中。然而,当我尝试这个时,我得到了 $injector undefined 错误,我猜是因为服务返回速度不够快:

    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;
        }
    }
    

    是否需要修复这个问题,或者我必须在每个控制器中重复jsonp请求? Here is a fiddle .

    1 回复  |  直到 7 年前
        1
  •  2
  •   jeff    10 年前

    虽然这不是一个漂亮的解决方案,但这应该对你有用。我添加了一些非常基本的缓存。我没有在angular中使用过jsonp,在$http配置中设置缓存似乎不起作用。这会是一个更好的选择。

    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;
    
        }
    ]);
    

    现在,在控制器内部,您可以执行以下操作:

    app.controller('someController', [ 'eventsFactory', 
        function( eventsFactory) {
    
            eventsFactory.getEvent().then(function( data ) {
                console.log( data );
            });
    
        }
    ]);