5

My code has the following:

.service('testService', TestService)
.service('userService', UserService)
.constant("appConstant", {
    appName: "My App",
    appVersion: 2.0,
    baseUrl: "http://localhost:3048",
    Action: {
        None:0,
        Registering: 1,
        Authenticating: 2
    }
});

Is there a way I can extract the constant object into a different .ts file and include that?

1 Answer 1

8

Yes. You can have the config in an external file. The simplest approach would be to do something like this:

class Constants
{
    static get Default():any {
        return {
            appName: "My App",
            appVersion: 2.0,
            baseUrl: "http://localhost:3048",
            Action: {
                None:0,
                Registering: 1,
                Authenticating: 2
            }
        };
    }
}

And then you can access it via Constants.Default. So your constant method in angular would look like:

.constant("appConstant", Constants.Default);

A more Typescript way would be to return types instead of the object literal in the default() getter. So you can go ahead and refactor my example to do that if you want.

Sign up to request clarification or add additional context in comments.

3 Comments

How would you refactor this to return the types in the default getter?
Probably he meant to return an instance of concrete type instead of any.
not really as constant for typescript so no TS error with this

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.