Reputation: 8960
In my Angular app I have defined a constant such as:
var app = angular.module('app', ['ngTagsInput'])
.constant('API', 'https://www.example.com/api/v1')
})();
However I want this API URL to be dependant on a constant I have set above, namely:
var WORKING_ON_ENV = "dev";
So I've tried to implement this using the following - however its not working - is this actually possible with Angular constants?:
.constant('API', function() {
if (WORKING_ON_ENV == "prod") {
return 'https://www.example.com/api/v1'
} else {
return 'https://www.example.com/api/v2'
}
})
Any advice appreciated.
Thanks.
Upvotes: 1
Views: 1188
Reputation: 48968
You can use an IIFE (Immediately Invoked Function Expression)
.constant('API',
(function() {
if (WORKING_ON_ENV == "prod") {
return 'https://www.example.com/api/v1'
} else {
return 'https://www.example.com/api/v2'
}
//Immediately invoke it
})()
)
Upvotes: 4
Reputation: 691943
Your code initializes the API constant to a function. What you want is to initialize it to the value returned by that function:
function getApi() {
if (WORKING_ON_ENV == "prod") {
return 'https://www.example.com/api/v1'
} else {
return 'https://www.example.com/api/v2'
}
}
.constant('API', getApi());
But this can be inlined:
.constant('API', WORKING_ON_ENV == "prod" ? 'https://www.example.com/api/v1' : 'https://www.example.com/api/v2');
Upvotes: 0
Reputation: 104785
You can use a ternary:
var app = angular.module('app', ['ngTagsInput'])
.constant('API', (WORKING_ON_ENV == "prod" ? 'https://www.example.com/api/v1' : 'https://www.example.com/api/v2'))
})();
Upvotes: 3