【问题标题】:How can I use the Angular $http service to retrieve simple data from the MongoDB REST API?如何使用 Angular $http 服务从 MongoDB REST API 检索简单数据?
【发布时间】:2016-09-29 13:31:48
【问题描述】:

我有一个简单的 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 动态创建了哪个回调?

【问题讨论】:

    标签: angularjs mongodb rest callback jsonp


    【解决方案1】:

    我实现了jsonpInterceptor,如下所述: 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);
    }
      };
    })
    

    His Plunker

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-01-02
      • 2016-01-26
      • 2016-11-08
      • 1970-01-01
      • 2021-09-08
      • 2012-10-28
      • 2021-07-22
      • 1970-01-01
      相关资源
      最近更新 更多