1

I am trying to build an object with keys that are defined in an environment file, so the keys will change based on the environment.

import { environment } from '../environments/environment'

export abstract class AbstractAPIService {
    fieldValues[environment.stateDropdownID] = ['Al', 'AK', 'CT', ....]
}

However, the compiler is giving the following error: '=' expected.

Is it possible to do something like this in Angular 4 or TypeScript in general?

Thanks!

3
  • 1
    I think you just can't do this in the class properties portion, but it looks to be possible in the constructor. See if this works for you. Commented Aug 10, 2017 at 20:46
  • That is pretty much just what I was looking for. If you want to post that example as an answer I will accept. Commented Aug 10, 2017 at 20:51
  • Sounds good, posting that answer. Thanks! Commented Aug 10, 2017 at 20:56

3 Answers 3

3

You will not be able to perform this dynamic key assignment in the Parameter properties of the class, you would however be able to achieve this in the constructor or methods of the class. It would work like this:

import { environment } from '../environments/environment'

export abstract class AbstractAPIService {
    fieldValues: object = {};

    constructor() {
        this.fieldValues[environment.stateDropdownID] = ['Al', 'AK', 'CT', ....];
    }
}

Here is a plunker demonstrating the functionality in a simple Angular sample application.

Hopefully that helps!

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

Comments

1

Angular runs in the browser, so there isn't really an environment, however you could insert your env variables in config files when you build the app like in this answer or have different values based on if it's dev or prod stage of the app by using isDevMode API

1 Comment

Providing the environment does seem like a better approach than importing in each component. However, I am still not sure how to add key/value pairs to an object if the key is a variable
1

I'd recommend doing this in the constructor as Alexander suggested, but it actually is possible to assign it directly if you really want to:

import { environment } from '../environments/environment'

export abstract class AbstractAPIService {
    fieldValues = {
        [environment.stateDropdownID]: ['Al', 'AK', 'CT', ....]
    }
}

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.