Angular 5 枚举(Enum)使用方法及代码疑问咨询
在Angular 5中使用枚举的正确姿势
首先,我把两种最常见的枚举使用场景拆解清楚,你对照自己的情况来调整就行:
1. 仅在当前组件内使用枚举
如果这个枚举只给当前组件用,直接在组件TS文件里定义就行,不用额外导入:
import { Component, OnInit } from '@angular/core'; import { Observable } from 'rxjs'; // 直接在组件文件内定义枚举 enum DisplayType { Something, Another, More } @Component({ selector: 'app-your-component', templateUrl: './your-component.component.html', styleUrls: ['./your-component.component.css'] }) export class YourComponent implements OnInit { constructor() { } ngOnInit() { // 直接通过枚举名访问枚举值调用函数 this.someFunction(DisplayType.Something).subscribe(() => { // 这里写你的订阅回调逻辑 }); } someFunction(displayType: DisplayType): Observable<any> { // 可以根据枚举值做分支处理 switch(displayType) { case DisplayType.Something: console.log('处理Something场景'); break; case DisplayType.Another: console.log('处理Another场景'); break; default: console.log('默认处理'); } // 返回一个Observable示例 return new Observable(observer => { observer.next(); observer.complete(); }); } }
2. 跨组件/服务共享枚举(更实用的场景)
如果多个组件或服务都要用到这个枚举,最好把它抽出来单独管理,方便统一维护:
步骤1:定义共享枚举
你可以选择把枚举放在服务文件里,或者单独建一个enums.ts文件专门存所有枚举:
- 放在服务文件的示例(比如
your.service.ts):
// your.service.ts import { Injectable } from '@angular/core'; // 导出枚举,让外部可以导入 export enum DisplayType { _0 = 0, Something = 1, Another = 2, More = 3 } @Injectable({ providedIn: 'root' }) export class YourService { // 服务的其他业务逻辑... }
- 单独建
enums.ts文件的示例:
// enums.ts export enum DisplayType { Something, Another, More } // 还可以加其他枚举 export enum StatusType { Active, Inactive }
步骤2:在组件中导入并使用
在需要的组件TS文件里导入枚举,之后就可以直接用了:
import { Component, OnInit } from '@angular/core'; import { Observable } from 'rxjs'; // 从服务文件导入,或者从单独的enums文件导入,注意路径要正确 import { DisplayType } from './your.service'; // 或者 import { DisplayType } from './enums'; @Component({ selector: 'app-your-component', templateUrl: './your-component.component.html', styleUrls: ['./your-component.component.css'] }) export class YourComponent implements OnInit { constructor() { } ngOnInit() { // 直接使用枚举值 this.someFunction(DisplayType.Something).subscribe(() => {}); // 自定义数值的枚举也一样用,还支持反向映射 console.log(DisplayType._0); // 输出0 console.log(DisplayType[0]); // 输出"_0",这个在把后端返回的数值转成枚举名时很有用 } someFunction(displayType: DisplayType): Observable<any> { // 逻辑处理... return new Observable(observer => { observer.next(); observer.complete(); }); } }
几个小提醒
- 枚举默认从0开始自动赋值,如果你需要自定义数值,直接像服务里那样
_0 = 0指定就行。 - 导入时一定要确认路径正确,比如同级目录用
./xxx,上级目录用../xxx,避免路径错误导致找不到枚举。 - 如果是在模板里要用到枚举,需要把枚举赋值给组件的一个公共属性,比如
public displayType = DisplayType;,这样模板里就能用*ngIf="someValue === displayType.Something"了。
内容的提问来源于stack exchange,提问作者Smokey Dawson
相关产品推荐
相关产品推荐

