Question

This question has less to do with how to do something, but more about best practices and what do others do?

I have a few services where I am using some kind of an external API (in this case the session storage api in the browser), where I am reusing the same constant string, the name of the company and the application, let's call it "ACME.Storage.", and this I want to prepend at the start of every "key" string. I see my options as:

  1. I can just reuse the string "ACME.Storage." in every call.
  2. I can create a JavaScript function where I create a new storage object that is configured with "ACME.Storage." once. That way, "ACME.Storage." appears once in my code.
  3. I can create a local variable ans store "ACME.Storage." in it, then reuse that. Again, the string literal appears only once in my code.
  4. I can create a separate javascript object that I can share.
  5. I can use an AngularJS "constant"
  6. I can add as a field to the app of config file.
  7. I can store it somewhere where localized literal strings (even though this particular string isn't localized) and get it through a translation service.

I'm leaning toward using the "constant" service 'cause it's the one that's easily injectable. My only concern is that it's less encapsulated than some of the other options.

Opinions on the best practice?

Was it helpful?

Solution

To expand upon what Whishler posted, you can (and probably should) use the Constant module that Angular provides. Complete docs are found here: http://docs.angularjs.org/api/ng/type/angular.Module. Services are a common place for constants, but the Constant modules get applied before other provide methods. Another option would be Value, but it does pretty much the same thing.

OTHER TIPS

Generally, I put constants into a service.

Depending what I'm doing, I may create a service that does nothing but store related constants. Or I may add them to another service representing a 'model'.

I'll also add that JavaScript doesn't officially have constants; so unless you wrote some code--such as your own accessors--you're just dealing with a variable that could be changed during the execution.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top