【问题标题】:Angular Service JSONP Request with Custom Callback带有自定义回调的 Angular 服务 JSONP 请求
【发布时间】:2015-04-29 14:21:40
【问题描述】:

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

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.

【问题讨论】:

    标签: angularjs jsonp angular-services


    【解决方案1】:

    虽然这不是一个漂亮的解决方案,但它应该适合您。我添加了一些非常基本的缓存。我没有在 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 );
            });
    
        }
    ]);
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-07-09
    • 2013-12-07
    • 1970-01-01
    • 1970-01-01
    • 2017-12-30
    • 2015-11-04
    • 1970-01-01
    • 2015-01-31
    相关资源
    最近更新 更多