如何使用 Angular $http 服务从 MongoDB REST API 中检索简单数据



我有一个简单的MongoDB,它存储了可以在公司范围内访问的临时虚拟数据。

我可以通过以下方式成功查询数据:

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

我的问题是Mongo的REST接口期待查询参数jsonp=my_callback,而Angular的$http服务期待查询参数callback=JSON_CALLBACK。 然后 Angular 将JSON_CALLBACK转换为自己的函数,在本例中angular.callbacks._0(但如果页面上有更多的回调,它将是 angular.callbacks._1angular.callbacks._2 等)。 我怎样才能告诉 Mongo Angular 动态创建了哪个回调?

我实现了如下所述的jsonpInterceptor:如何自定义设置角度JS JSONP回调名称

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

他的普伦克

最新更新