Angular 4/Typescript中的动态键值分配 [英] Dynamic Key Value Assignment in Angular 4 / Typescript
问题描述
我正在尝试使用环境文件中定义的键来构建对象,因此键会根据环境而变化.
从"../environments/environment"导入{环境}导出抽象类AbstractAPIService {fieldValues [environment.stateDropdownID] = ['Al','AK','CT',....]}
但是,编译器给出了以下错误:预期为'='.
一般可以在Angular 4或TypeScript中做类似的事情吗?
谢谢!
您将无法在类的Parameter属性中执行此动态键分配,但是您将能够在以下方法的构造函数或方法中实现此目的:班上.它将像这样工作:
从"../environments/environment"导入{环境}导出抽象类AbstractAPIService {fieldValues:object = {};Constructor(){this.fieldValues [environment.stateDropdownID] = ['Al','AK','CT',....];}}
这是 plunker ,展示了一个简单的Angular示例应用程序中的功能./p>
希望有帮助!
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!
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!
这篇关于Angular 4/Typescript中的动态键值分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!