Reputation: 73938
I cannot retrieve string
from myConstant
in a service.
What am I doing wrong here and how to fix it? Please provide me sample of code.
// Define Angular App
var app = angular.module('App', ['ngRoute', 'LocalStorageModule', 'angular-loading-bar']).constant('myConstant', {
string: 'myString',
size: 30
});
'use strict';
app.factory('devicesService', ['$http', 'myConstant', function ($http) {
var serviceBase = myConstant.string; // PROBLEM HERE
...
Upvotes: 1
Views: 278
Reputation: 27043
You can add constants to your application using either constant
or value
.
Both are exactly the same with just a slight difference. That is values inside constant
can never be changed, while values inside value
can be changed using decorator
.
Example:
var app = angular.module('app', []);
app.constant('MY_CONSTANT', {
value1: 'value 123',
});
app.variable('MY_VARIABLE', {
value1: 'value 456',
});
app.controller('MainCtrl', function ($scope, MY_CONSTANT, MY_VARIABLE) {
console.log('constant: ', MY_CONSTANT.value1);
console.log('variable: ', MY_VARIABLE.value1);
});
Upvotes: 2
Reputation: 41533
Your code works just fine if you do add the constant as a parameter in yout factory function:
app.factory('devicesService', ['$http', 'myConstant', function ($http, myConstant) {
In your example, you only added it to the min-safe array, but not in the actual function.
I'm guessing that that's why you had a problem there, because the function wasn't aware of any myConstant
variable.
Upvotes: 1
Reputation: 7475
here is example for using constant in angular: add it to app.js
.constant('AUTH_EVENTS', {
AuthenticatedSuccess: 'auth-user-success',
})
in you controller:
.controller('ApplicationController', function ($scope, AUTH_EVENTS) {
console.log(AUTH_EVENTS.AuthenticatedSuccess);
}
Upvotes: 2