【问题标题】:Angular : enum is undefinedAngular:枚举未定义
【发布时间】:2020-09-15 13:31:04
【问题描述】:

我正在尝试在 Angular 中使用枚举,但我的枚举对象似乎未定义。

枚举

export enum Section {
    Equals="Equals",
    NEquals="NEquals",  
    }

组件

 import { Component, OnInit } from '@angular/core';
 import { Section } from './model/Section.model';

@Component({
  selector: 'app-project'})


export class ProjectComponent implements OnInit {

    section = Section;
     
ngOnInit() {
    console.log(this.section);
      }  
}

当我执行"console.log(this.section)" 时,控制台显示未定义。 请问有什么解决办法吗?

【问题讨论】:

  • 我想你必须重新启动你的ng serve。我记得 cli 在获取新添加的枚举时遇到问题
  • 您在登录 Section 时看到了什么? console.log(Section)
  • @ArmenStepanyan 它在我使用 console.log(Section) 时有效,但我想使用一个对象,因为我将在下拉列表中使用它。有什么解决办法吗?
  • @PoulKruijt 如何重启 ng 服务?
  • @firas1 实际上您的代码是正确的,但请尝试将这一行 section = Section 移动到 ngOnInit()

标签: angular typescript enums frontend


【解决方案1】:

我们使用 TypeScript 命名空间values() 方法 添加到 Section 枚举中。

你可以看现场演示here

section.enum.ts

export enum Section {
  Equals = "Equals",
  NEquals = "NEquals"
}

export namespace Section {
  export function values() {
    return Object.keys(Section).filter(
      type => isNaN(<any>type) && type !== "values"
    );
  }
}

app.component.ts

import { Component } from "@angular/core";
import { Section } from "./section.enum";

@Component({
  selector: "my-app",
  template: `
    <p>
      <select>
        <option *ngFor="let type of section.values()">
          {{ type }}
        </option>
      </select>
    </p>
  `
})
export class AppComponent {
  section = Section;
  ngOnInit() {
    console.log(Section);
    console.log(Section.Equals);
    console.log(Section["Equals"]);
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-01-18
    • 1970-01-01
    • 1970-01-01
    • 2019-10-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-10
    相关资源
    最近更新 更多