Angular Service JSONP Request with Custom Callback
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.
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 );
});
}
]);
链接地址: http://www.djcxy.com/p/47558.html
上一篇: JSONP注入的脚本没有调用回调