How can I change the base URL of an AngularJS HTTP call?

后端 未结 4 1939
灰色年华
灰色年华 2021-02-20 10:21

My application calls $HTTP many times like this:

    this.$http({
        method: this.method,
        url: this.url
    })

The this.url is alw

相关标签:
4条回答
  • 2021-02-20 10:53

    I tend to keep my urls close to where they are needed. So if I have a service, then I'd keep the base url there; like this: this.rootUrl = '/api/v1/';

    This allows me to have additional contextual methods that 'extend' the url.

    For example:

    this.getBaseUrl = function(client_id, project_id) {
        return this.rootUrl + 'clients/' + client_id + '/projects/' + project_id + '/';
    };
    

    Which I can then use like this:

    this.createActivity = function(client_id, project_id, activity_name, callback) {
        $http.post(this.getBaseUrl(client_id, project_id) + 'activities', {activity: {name: activity_name}})
            .success(callback)
            .error(this.handlerError);
    };
    

    or like this (within the same service):

    this.closeActivity = function(activity_id, callback){
        $http.get(this.rootUrl + 'close_activity/' + activity_id)
            .success(callback)
            .error(this.handlerError);
    };
    

    -harold

    0 讨论(0)
  • 2021-02-20 11:07

    I found a alternative solution instead of <base> tag: written in coffeescript

    $httpProvider.interceptors.push ($q)->
      'request': (config)->
        if config.url.indexOf('/api') is 0
          config.url = BASE_URL+config.url
        config
    
    0 讨论(0)
  • 2021-02-20 11:11

    set baseUrl in $rootScope:

    app.run(function($rootScope) {
        $rootScope.baseUrl = "https://newserver.com";
    });
    

    add $rootScope into your app's controllers:

    app.controller('Controller', ['$rootScope', function($rootScope){
        ...
    
    this.$http({
        method: this.method,
        url: $rootScope.baseUrl + this.url
    })
    
    0 讨论(0)
  • 2021-02-20 11:13

    I usually keep settings in angular constants and inject them to services.

    0 讨论(0)
提交回复
热议问题