Using a Relative Path for a Service Call in AngularJS

后端 未结 9 2073
别跟我提以往
别跟我提以往 2020-11-28 03:51

I have the following code, which was working fine until I deployed to a test server:

$scope.getUserList = function (userName) {
    $http({
        method: \         


        
9条回答
  •  死守一世寂寞
    2020-11-28 04:02

    I would suggest defining a module that contains a global config that you can then pass around your application:

    // Module specific configuration
    angular.module('app.config')
      .value('app.config', {
        basePath: '/' // Set your base path here
      });
    

    Then you can access this from anywhere within your application thanks to AngularJS dependency injection:

    // Make sure your config is included in your module
    angular.module('app', ['app.config']);
    
    // Access your config e.g. in a controller
    angular.module('app')
      .controller('TestCtrl', ['$scope','app.config', function($scope, config){
    
        // Use config base path to assemble url
        $scope.url = config.basePath + 'GetUserList';
        ...
      }]);
    

    Whenever the base path changes (e.g. when you change to another server or host), you just need to change it in your global config and you're done.

提交回复
热议问题