Best way to override module values/constants in angularJS

前端 未结 3 2365
一个人的身影
一个人的身影 2021-02-20 07:03

I have written a module in angularJS that encapsulates all the backend communications. For greater flexibility I have the api prefix as a constant value on the module (could be

3条回答
  •  一个人的身影
    2021-02-20 07:50

    Our module

    angular.module("data", [])
      .constant('apiPrefix', '/api/data');
    

    We can override constant fully, like value.

    angular.module('myapp', ['data'])
      .constant('apiPrefix', '/api2/data');
    

    also we can override fully in config

    angular.module('myapp', ['data'])
        .config(function ($provide) {
            $provide.constant('apiPrefix', '/api2/data');
        });
    

    also we can override fully or partially (if object) in run

    angular.module('myapp', ['data'])
        .run(function (apiPrefix) {
            apiPrefix = '/api2/data';
        });
    

    But if we want to override constant with object partially in config (not in run), we can do something like this

    angular.module("module1", [])
        .constant('myConfig', {
            param1: 'value1' ,
            param2: 'value2'
        });
    
    angular.module('myapp', ['data'])
        .config(function ($provide, myConfig) {
            $provide.constant(
                'myConfig', 
                angular.extend(myConfig, {param2: 'value2_1'});
            );
        });
    

提交回复
热议问题