Is it possible to inject a provider / dependency into an Angular constant?

-1

We are creating a constant in our project developed with the help of AngularJS, this in order to avoid repeated code. However, the question arises whether it is possible to inject a provider or dependency within that constant, and the question arises because we wanted to use one of the attributes to manipulate the messages with Angular-Growl and it was not possible. In the case of SweetAlert it was possible without problems.

(function () {
   'use strict';

    angular.module('mytodoApp').constant("appConstant", {
       'FILTRO_TABLAS': [{ name: '5', value: '5' }, { name: '10', value: '10' },
           { name: '20', value: '20' }, { name: '30', value: '30' },
           { name: '50', value: '50' }],
       'MSG_LOADING': function (title) {
           swal({
               title: title,
               allowOutsideClick: false,
               allowEscapeKey: false
           });
       },
       'MSG_SYSTEM_ERROR': function (title, type) {
           swal('Hubo un problema', title, type);
        }
   })
})();

In this case, when you inject the constant appConstant in any controller, the swal (which are the messages generated with SweetAlert) work fine, however, by adding this:

'MSG_GROWL_ERROR': function(title) {
  growl.error("<div><i class='glyphicon glyphicon-ok' style='padding-left:15px;font-size: 20px;'></i>&nbsp;&nbsp;<span><strong>Error!</strong>" +title+"</div>");

It appears in the browser console that a dependency called Growl is not known. I tried to inject it into the constant and automatically the application explodes.

    
asked by César Gómez 30.08.2016 в 17:17
source

1 answer

1

As the documentation says, you can not inject other services into a constant ( source ). Which is logical, because otherwise, it would not be a constant.

However, you can use a service itself. If you want to avoid modifying the FILTRO_TABLAS object, you can use Object.freeze .

angular.service('miservicio', ['growl', function(growl) {
   this.MSG_GROWL_ERROR = function(title) {
        growl.error("<div><i class='glyphicon glyphicon-ok' style='padding-left:15px;font-size: 20px;'></i>&nbsp;&nbsp;<span><strong>Error!</strong>" +title+"</div>");
   }

   this.FILTRO_TABLAS = { constante: 20 };
   Object.freeze(this.FILTRO_TABLAS);
});
    
answered by 30.08.2016 / 18:30
source