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!

Jeroen
  • 1,168
  • 1
  • 12
  • 24
Mac
  • 1,143
  • 6
  • 21
  • 45

3 Answers3

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!

Alexander Staroselsky
  • 37,209
  • 15
  • 79
  • 91
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

LLL
  • 3,566
  • 2
  • 25
  • 44
  • 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 – Mac Aug 10 '17 at 20:35
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', ....]
    }
}
John Montgomery
  • 6,739
  • 9
  • 52
  • 68