AngularJS Remote Client Properties are divided into controllers / services

I want to create an AngularJS web client for which the REST backend can be hosted on another server. Therefore, basically I think about the presence of the property input field in the interface, where for each session I will enter the base REST URL (for example, http://localhost:8080/backend/rest/)

Is there any best practice for sharing the base url among all controllers / factories / services so that it is included for all $ http requests?

+3
source share
3 answers

I would set up an HTTP interceptor service that simply adds a value to the URL passed to the $ http service. Something like the following (not verified):

// register the interceptor as a service
$provide.factory('pathPrependerInterceptor', function() {
    var _path = 'http://localhost:8080/backend/rest'; // default value
    return {
        request: function(config) {
            config.url = _path + config.url
            return config;
        },
        setPath: function(path) {
            _path = path;
        }
    }
});

$httpProvider.interceptors.push('pathPrependerInterceptor');
+2
source

, interceptors. AngularJs.

, , url :

var app = angular.module('MyApp',[]);

app.config(['$httpProvider', function($httpProvider) {
    $httpProvider.interceptors.push(function($q) {
        return {
            'request': function(config) {
                config.url = "http://api.openweathermap.org/data/2.5/" + config.url
                return config;
            }
        };
    });
}]);

, .

JSFiddle, .

+2

Other answers are taken from a more experienced bunch, so take this with a pinch of salt, but they seem redundant to me. You are setting up an application variable that requires an injection. Using

module.value("baseRestUrl", ...)

allows you to enter baseRestUrlwherever needed.

+2
source

All Articles