userMod2
userMod2

Reputation: 8960

Angular - Constant Variable Decided Conditionally

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

Answers (3)

georgeawg
georgeawg

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

JB Nizet
JB Nizet

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

tymeJV
tymeJV

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

Related Questions