Nice programing

Angularjs에 다른 상수로 상수를 정의하는 방법이 있습니까?

nicepro 2020. 10. 15. 21:38
반응형

Angularjs에 다른 상수로 상수를 정의하는 방법이 있습니까?


다른 상수로 상수를 정의하려고하는데 필요한 상수가 필요할 때 초기 상수가 준비되지 않았기 때문에 수행 할 수없는 것 같습니다. 이것이 전혀 불가능한지 확인하고 싶습니다.

현재 나는 이런 식으로 상수가 있습니다.

angular.module('mainApp.config', [])
    .constant('RESOURCE_USERS_DOMAIN', 'http://127.0.0.1:8008')
    .constant('RESOURCE_USERS_API', 'http://127.0.0.1:8008/users')
    // Specific routes for API
    .constant('API_BASIC_INFORMATION', RESOURCE_USERS_API + '/api/info')
    .constant('API_SOCIAL_NETWORKS', RESOURCE_USERS_API + '/api/social')
    ;

두 번째 두 상수는 내가 달성하고 싶은 것입니다.


컨트롤러, 서비스 및 기타 간의 종속성을 정의하는 각진 방법은 DI (종속성 주입)입니다. 따라서 서비스 B에 의존하는 컨트롤러 A가있는 경우 다음과 같이 만들어야합니다.

var myApp = angular.module("exampleApp",[]);

myApp.controller("aCtrl", function(serviceB){
    //Controller functionally here
});

angular는 serviceB 종속성을 확인하고 해당 이름으로 만든 서비스를 찾습니다. 생성하지 않으면 오류가 발생합니다.

따라서 상수 B에 의존하는 상수 A를 생성하려면 A가 B에 의존한다고 angular에 알려야합니다.하지만 상수는 종속성을 가질 수 없습니다. 상수는 함수를 반환 할 수 있지만 DI는 상수에 대해 작동하지 않습니다. Fiddle을 확인하여 DI가 작동하는 방법을 확인할 수 있습니다.

따라서 질문에 대답하면 다른 상수로 상수를 정의 할 수 없습니다.

하지만 다음과 같이 할 수 있습니다.

angular.module('projectApp', [])
  .constant('domain','http://somedomain.com')
  .constant('api','/some/api/info')
  .service('urls',function(domain,api){ this.apiUrl = domain+api;})

  .controller('mainCtrl',function($scope,urls) {

      $scope.url = urls.apiUrl;

  });

바이올린작동하는지 확인하십시오 .

DI에 대해 더 알고 싶다면이 게시물을 확인하세요 .

이것이 귀하의 질문에 답이되기를 바랍니다.


이를 수행하는 쉬운 방법은 다음과 같습니다.

var myApp = angular.module("exampleApp",[]);

myApp.constant('RESOURCES', (function() {
  // Define your variable
  var resource = 'http://127.0.0.1:8008';
  // Use the variable in your constants
  return {
    USERS_DOMAIN: resource,
    USERS_API: resource + '/users',
    BASIC_INFO: resource + '/api/info'
  }
})());

그리고 다음과 같은 상수를 사용하십시오.

myApp.controller("ExampleCtrl", function(RESOURCES){
  $scope.domain = RESOURCES.USERS_DOMAIN;
});

크레딧 : 링크


나는 이렇게한다 :

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

constants.factory("Independent", [function() {
   return {
      C1: 42
   }
}]);

constants.factory('Constants', ["Independent", function(I) {
   return {
      ANSWER_TO_LIFE: I.C1
   }
}]);

공급자에서 상수에 액세스 할 필요가없는 한 정상적으로 작동합니다.

.constant('HOST', 'localhost')
.factory('URL', function(HOST) { return "http://" + HOST })

If you need access to you constants in providers, then I guess you have to do some more work:

.constants('HOST', 'localhost')
.provider('DOMAIN', function(HOST) {
    var domain = "http://" + HOST;
    this.value = function() { return domain };
    this.$get = this.value;
 })
 .provider("anyOtherProvider", function(DOMAINPovider) {
     var domain = DOMAINProvider.value();
 };
 .factory("anyOtherService", function(DOMAIN) {
 })

Can't tell for sure if that's (im)possible. But a workaround would be to define the base constants as regular constants, and the higher-order ones as services using closures to make sure they cannot be altered.

Rough example:

angular.module('myApp').constant('BASE_CONSTS',{
    'FIRST_CONST': '10',
    'SECOND_CONST': '20'
});

angular.module('myServices').factory('MyServiceName', ['BASE_CONSTS', function ('BASE_CONSTS') {
    var SECOND_ORDER_CONST = BASE_CONSTS.FIRST_CONST * 100;
    return {
        GET_SECOND_ORDER_CONST: function() {
            return SECOND_ORDER_CONST;
        }
    }
}]);

And use it after injecting the service:

MyServiceName.GET_SECOND_ORDER_CONST();

Not very elegant, but should get the job done.


The solution provided by @Linkmichiel is good, but if you desperately want to use one constant inside another, you can combine them in the config block:

angular.module("exampleApp", [])

.constant('BASE_URL', 'http://127.0.0.1:8008')

.constant('RESOURCES', {
  USERS_DOMAIN: '',
  USERS_API: '/users',
  BASIC_INFO: '/api/info'
})

.config(function(BASE_URL, RESOURCES) {
  for (prop in RESOURCES) {
    RESOURCES[prop] = BASE_URL + RESOURCES[prop];
  }
})

.controller('WhatIsInResourcesController', function($scope, RESOURCES) {
  $scope.RESOURCES = RESOURCES;
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="exampleApp">
  <div ng-controller="WhatIsInResourcesController">
    <pre>{{ RESOURCES | json }}</pre>
  </div>
</div>

After the config phase, all constants will be setup correctly (try out the snippet).

The moral of the story is: Angular is so cool that you can even change the constants.

참고URL : https://stackoverflow.com/questions/18494050/is-there-a-way-in-angularjs-to-define-constants-with-other-constants

반응형