用恒定值在Angular中定义接口

时间:2018-06-29 12:22:20

标签: angular

在Angular中,如何定义具有常量值的接口?即,一个“州”界面,其中包含澳大利亚的所有州。/

我可以这样:

interface State {
  name: string;
}

然后在我的组件中:

states: State[];

this.states = [
        {name: "New South Wales"},
        {name: "Victoria"},
        {name: "Northern Territory"},
        {name: "Victoria"}
];

但是我想将初始化合并到我的Interface中,以便可以将其包含在多个组件中。实现此目标的最佳方法是什么?

3 个答案:

答案 0 :(得分:3)

接口用于定义属性,而不是常量。.常量用于定义常量。

interface State {  name: string }

export const STATES: State[] = [..all of the states]

然后仅在需要的地方导入STATES。在理想的世界中,您可以使用诸如immutable.js之类的方法来确保它永远不会发生突变,但是除了将其包装在服务中并以这种方式进行保护之外,不幸的是,您可以采取其他许多措施来防止发生突变。

答案 1 :(得分:2)

如果您的接口只是状态的恒定值,则可以仅对状态使用Enums代替接口。

export enum States {
 SYDNEY= "SYDNEY", 
 MELBOURNE= "MELBOURNE",
 .....
}

,并在您要访问此值的任何地方使用此Enum。
-编辑
另外,如果您想向界面添加更多信息,则可以执行以下操作:

export interface StateDetails {
 name: States; // <--- which is the constant values from the enum.
 population: number;
 ... and so on. 
}

答案 2 :(得分:2)

为什么不定义服务方法以返回默认值并在构造函数中调用该方法。

getState(): State[] {

   return [
        {name: "New South Wales"},
        {name: "Victoria"},
        {name: "Northern Territory"},
        {name: "Victoria"}
   ];
}

在组件中

constructor(private myService: MyService){
  this.state - this.myService.getState()
}