带有自定义回调的 Angular 服务 JSONP 请求 [英] Angular Service JSONP Request with Custom Callback
问题描述
我从具有自定义回调函数的 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;
}
但是,我现在想在服务中执行此操作,以便我可以一次性加载数据并将其注入到我的所有控制器中.然而,当我尝试这个时,我得到一个 $injector undefined 错误,我我猜是因为服务返回的速度不够快:
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 请求?这是一个小提琴.
Is there anyway to fix this or will I have to repeat the jsonp request in each controller? Here is a fiddle.
推荐答案
虽然它不是一个漂亮的解决方案,但它应该适合您.我添加了一些非常基本的缓存.我没有在 angular 中使用过 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 );
});
}
]);
这篇关于带有自定义回调的 Angular 服务 JSONP 请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!