Angular 角度:枚举未定义
我试图在angular中使用enum,但我的enum对象似乎未定义 枚举Angular 角度:枚举未定义,angular,typescript,enums,frontend,Angular,Typescript,Enums,Frontend,我试图在angular中使用enum,但我的enum对象似乎未定义 枚举 export enum Section { Equals="Equals", NEquals="NEquals", } 组件 import { Component, OnInit } from '@angular/core'; import { Section } from './model/Section.model'; @Component({
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)”
时,控制台显示undefined。
有什么解决方案吗?我们使用TypeScript命名空间将values()方法添加到部分枚举中 您可以看到现场演示 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"
);
}
}
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"]);
}
}
导出枚举部分{
Equals=“Equals”,
NEquals=“NEquals”
}
导出命名空间部分{
导出函数值(){
返回对象.keys(节).filter(
类型=>isNaN(类型)&&type!==“值”
);
}
}
应用程序组件.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"
);
}
}
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"]);
}
}
从“@angular/core”导入{Component};
从“/Section.enum”导入{Section}”;
@组成部分({
选择器:“我的应用程序”,
模板:`
{{type}}
`
})
导出类AppComponent{
截面=截面;
恩戈尼尼特(){
控制台日志(部分);
console.log(Section.Equals);
console.log(第[“Equals”]节);
}
}
我想您必须重新启动您的ng服务。我记得cli在获取新添加的枚举时遇到问题您在登录部分时看到了什么console.log(Section)
@ArmenStepanyan当我使用console.log(Section)时它可以工作,但我想使用一个对象,因为我将在下拉列表中使用它。有什么解决方案吗?@PoulKruijt如何重新启动ng serve?@firas1实际上您的代码是正确的,但请尝试将此行section=section
移动到ngOnInit()