简体   繁体   English

数组的打字稿枚举

[英]typescript enum from array

Currently, I am getting an array of UserRole objects from the back-end. 目前,我正在从后端获取一组UserRole对象。 Each UserRole has an Id (int) and a Role (string). 每个UserRole都有一个ID(int)和一个Role(string)。

UserRoles[ ] looks like... UserRoles []看起来像...
 [ //{id, role} {1, Viewer}, {2, Owner}, {3, Admin} ] 
_models\\userRole.ts _models \\ userRole.ts
 export interface UserRole { id: number, role: string } 


home.component.ts home.component.ts
 export class HomeComponent implements OnInit { ... userRoles: UserRole[] constructor(...) { http.get<UserRole[]>(baseurl + "api/UserRoles/GetUserRoles").subscribe(result => { this.userRoles = result; }, error => console.error(error)); } ... } 


The issue: 问题:

I'd like to turn it into an enum for use in limiting what is presented to the user. 我想将其变成一个枚举,用于限制呈现给用户的内容。 For example, 例如,

 <div *ngIf="user.userRoleId >= userRoles.Owner "> 

Should I be sending something other than an array of objects up from the backend (which is an ASP.NET Core controller)? 我是否应该从后端(这是一个ASP.NET Core控制器)向上发送对象数组以外的东西?

Is there a way to generate the enum immediately from the api call? 有没有一种方法可以通过api调用立即生成枚举?

Or is there a way to convert the array of objects to an enum? 还是有一种方法可以将对象数组转换为枚举?

Thanks to the suggestion by Eliseo, here's what I ended up doing: 感谢Eliseo的建议,这就是我最终要做的事情:

I retrieved the UserRoles as an array, then did a foreach loop on that array, and added the roles and id to an object. 我将UserRoles检索为数组,然后对该数组进行了foreach循环,并将角色和ID添加到对象。

home.component.ts home.component.ts
 //imports export class HomeComponent implements OnInit { ... user: User; userRoles: any = {}; constructor(private userRoleService: UserRoleService, private alertify: AlertifyService) {} ngOnInit() { this.loadUserRoles(); } loadUserRoles() { this.userRoleService.getUserRoles().subscribe((res: UserRole[]) => { res.forEach(p => this.userRoles[p.role] = p.id); }); } 
userRole.service.ts userRole.service.ts
<div *ngIf="user.userRoleId >= userRoles.Owner ">
    ...
</div>
home.component.html implementation home.component.html实现
 <div *ngIf="user.userRoleId >= userRoles.Owner "> ... </div> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM