I have a simple MongoDB that stores temporary dummy data that is accessible company-wide.
I can successfully query the data via the following:
$http.jsonp("http://my_server/my_database/my_collection/?callback=JSON_CALLBACK&jsonp=angular.callbacks._0")
.then(getServersComplete)
.catch(getServersFailed);
function getServersComplete(response) {
var test = response.data;
//do stuff
}
function getServersFailed(error) {
$log.error('XHR Failed for getServers.\n' + angular.toJson(error.data, true));
}
My problem is that Mongo's REST interface is expecting the query parameter jsonp=my_callback
while Angular's $http
service is expecting the query parameter callback=JSON_CALLBACK
. Angular then translates JSON_CALLBACK
into its own function, in this case angular.callbacks._0
(but if there were more callbacks on the page, it would be angular.callbacks._1
, angular.callbacks._2
, etc.). How can I tell Mongo which callback Angular has dynamically created?
I implemented the jsonpInterceptor
as described here:
How to Custom Set AngularJS JSONP Callback Name
.factory('jsonpInterceptor', function($timeout, $window, $q) {
return {
'request': function(config) {
if (config.method === 'JSONP') {
var callbackId = angular.callbacks.counter.toString(36);
config.callbackName = 'angular_callbacks_' + callbackId;
config.url = config.url.replace('JSON_CALLBACK', config.callbackName);
$timeout(function() {
$window[config.callbackName] = angular.callbacks['_' + callbackId];
}, 0, false);
}
return config;
},
'response': function(response) {
var config = response.config;
if (config.method === 'JSONP') {
delete $window[config.callbackName]; // cleanup
}
return response;
},
'responseError': function(rejection) {
var config = rejection.config;
if (config.method === 'JSONP') {
delete $window[config.callbackName]; // cleanup
}
return $q.reject(rejection);
}
};
})