Setting Angular $resource Config Globally

ε祈祈猫儿з 提交于 2019-12-08 07:00:17

问题


Based on the following sample, how can I set the $resource timeout and headers globally? I have a number of $resource definitions like the following but I’d prefer to not repeat the basic config for each.

angular
    .module('myApp.services')
    .factory('myServices', myServices);

myServices.$inject = ['$resource'];

function myServices($resource) {
    return {
        serviceA: $resource('/api/serviceA', {
            serviceA_paramA: '@serviceA_valueA',
            serviceA_paramB: '@serviceA_valueB'
        }, {
            'get': {
                method: 'GET',
                timeout: 120000
            }
        }, {
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            }
        }),
        serviceB: $resource('/api/serviceB', {
            serviceB_paramA: '@serviceB_valueA',
            serviceB_paramB: '@serviceB_valueB'
        }, {
            'get': {
                method: 'GET',
                timeout: 120000
            }
        }, {
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            }
        })
    };
}

回答1:


Define your configuration object as a constant, then you can inject it into each service that needs it, and overwrite any properties that are specific to that service.

//Constant
angular.module('myApp')
  .constant('serviceConfigObject',
    {
      'get': {
        method: 'GET',
        timeout: 120000
      }
    }, {
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      }
    })

// Service
angular
    .module('myApp.services')
    .factory('myServices', myServices);

myServices.$inject = ['$resource', 'serviceConfigObject'];

function myServices($resource, serviceConfigObject) {
    return {
        serviceA: $resource('/api/serviceA', {
            serviceA_paramA: '@serviceA_valueA',
            serviceA_paramB: '@serviceA_valueB'
        }, serviceConfigObject),
        serviceB: $resource('/api/serviceB', {
            serviceB_paramA: '@serviceB_valueA',
            serviceB_paramB: '@serviceB_valueB'
        }, serviceConfigObject)
    };
}



回答2:


You may have a provider under .config(), .value() or .constant() module. Refer to this useful Gist which explains and provides sample code for all the different providers.

for simplicity, this is the .constant() example:

angular
    .module('myApp.constants')
    .constant("AppConstants", {
       "timeout" : 120000,
       "method"  : "GET",
       ....
       // define your kv structure here
    })

So now you can inject it in your module function. Hope this helps.



来源:https://stackoverflow.com/questions/30133415/setting-angular-resource-config-globally

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!