角服务JSONP请求与定义回调 [英] Angular Service JSONP Request with Custom Callback

查看:189
本文介绍了角服务JSONP请求与定义回调的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是从JSONP拉动饲料有定制的回调函数,的例如的:

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

反正是有解决这个问题,否则我将不得不重复每个控制器的JSONP请求? 这里是一个小提琴

推荐答案

虽然它不是一个漂亮的解决方案,这应该为你工作。我在一些非常基本的缓存增加。我没有用角JSONP,它似乎在$ HTTP配置设置缓存不起作用。这本来是一个更好的选择。

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

    }
]);

这篇关于角服务JSONP请求与定义回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆