【问题标题】:How to configure Angular.js to user default host?如何将 Angular.js 配置为用户默认主机?
【发布时间】:2014-05-26 20:03:05
【问题描述】:

例如,我有这个电话:

$http({method: 'GET', url: '/someUrl'}).
success(function(data, status, headers, config) {
  // this callback will be called asynchronously
  // when the response is available
}).
error(function(data, status, headers, config) {
  // called asynchronously if an error occurs
  // or server returns response with an error status.
});

我需要它来请求http://my-api-url.com/someUrl,但我不想到处输入它,因为它将来会改变。

如何全局配置?

【问题讨论】:

    标签: angularjs angularjs-http


    【解决方案1】:

    使用常量:

    var myApp = angular.module('myApp',[]);
    
    myApp.constant('myUrls', {
        someUrl: 'http://my-api-url.com/someUrl,',
    });
    
    mayApp.directive('myDirective', ['myUrls', function (myUrls) {
        return {
            ....
            // use myUrls.someUrl
            ....
        };
    }]);
    

    AngularJS Module

    【讨论】:

      【解决方案2】:

      我不认为你可以,这会削弱对其他 url 的任何其他调用,所以你可以做的是在指向你想要的主机的服务中设置一个主机变量,然后在每次调用中将你的 url 设置为。

      $http.get(service.host+'/somePath'}).
      success(function(data, status, headers, config) {
      
      }).
      error(function(data, status, headers, config) {
      
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-08-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多