سؤال

I created a config service to provide environment specific configurations. I'm using the $httpProvider to intercept and extend the request url with a API Base Url but how do i access the config service from within $httpProvider?

I've read about the $injector but i did not understand how to use it to solve my problem.

// pseudo code, not working
app.service('Config', function() {

    // configuration property object

    return {
        get: function (property) {
            return property
        }
    } 
});

app.config(function ($httpProvider, Config) {

    $httpProvider.interceptors.push(function ($q) {
        return {
            'request': function (config) {

                // extend config.url to add a base url to the request
                if (config.url.indexOf('api') !== -1) {
                    config.url = Config.get('root') + config.url;
                }

                return config || $q.when(config);
            }
        }
    });
});
هل كانت مفيدة؟

المحلول

Change this line:

app.config(function($httpProvider, Config) {

to:

app.config(function($httpProvider) {

and this line:

$httpProvider.interceptors.push(function($q) {

to:

$httpProvider.interceptors.push(function($q, Config) {

This works because the function you push to the interceptors is essentially an angular service that can be defined like this:

angular.app('app', [])
  .service('HttpInterceptor', function($q, Config) {
     return {
       request: function() {
         // Do whatever
       }
     };
  });

Which can be passed in the config function like this:

$httpProvider.interceptors.push('HttpInterceptor');

As long as your HttpInterceptor service does not call on $http or anything that depends on $http (... like $resource), you'll be fine. @Ye Liu was right in his comment that services are not allowed to be injected into the config function. However, services can be injected into other services.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top