如何自定义设置angularjs jsonp回调名称?

Pra*_*odh 9 jsonp angularjs

我必须通过angularjs从一些网站获取json数据.我已根据以下链接正确完成了所有事情.

我的问题是api不允许callback参数包含除字母,数字和_之外的任何字符.而且由于angular用"angular.callbacks._0"之类的东西取代了JSON_CALLBACK,因此不允许使用它.

如何为angularjs自定义此值?

解析angular.js中的JSONP $ http.jsonp()响应

谢谢

run*_*arm 11

回调名称在这里是硬编码的httpBackend.js#L55,因此您无法对其进行配置.

但是,您可以编写一个HTTP拦截器来解决它,如下所示:

.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);
    }
  };
})
Run Code Online (Sandbox Code Playgroud)

示例Plunker: http ://plnkr.co/edit/S5K46izpIxHat3gLqvu7?p =preview

希望这可以帮助.