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

后端 未结 4 1940
灰色年华
灰色年华 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

提交回复
热议问题