[英]Given a string value, how can I find if it is 'greater than' a value in a Typescript enumerated type?
I am implementing a very basic user roles, to disallow users with lower privileges from seeing certain parts of the site. 我实现了一个非常基本的用户角色,以禁止具有较低特权的用户查看网站的某些部分。 For example, the current user must be an Executive or higher or a given div will not render. 例如,当前用户必须是Executive或更高级别,否则给定的div将不会呈现。
I have a string value from the database representing the user's level eg "Executive", or "Owner". 我有一个表示用户级别的数据库中的字符串值,例如“ Executive”或“ Owner”。 I want to compare that to an enumerated type I have created: 我想将其与我创建的枚举类型进行比较:
enum systemRoles {
Staff,
Manager,
DeptMgr,
Executive,
Owner
}
...so that in an html template I can say: ...以便在html模板中我可以说:
<div *ngIf="userLevelIsAtLeast(systemRoles.Executive)">
to only render that div if the user has high enough privileges. 仅在用户具有足够高的特权时才渲染该div。 So, my pseudocode is: 所以,我的伪代码是:
<div *ngIf="userLevelIsAtLeast(systemRoles.Executive)>You are an executive or higher!</div>
.
.
userLevelIsAtLeast(user_level) {
return currentUser().level >= user_level
}
To be clear: if currentUser.level == "Executive"
, this should return true. 要明确:如果currentUser.level == "Executive"
,则应返回true。 if currentUser.level == "Owner"
, this should return true. 如果currentUser.level == "Owner"
,则应返回true。 if currentUser.level == "Staff"
, this should return false. 如果currentUser.level == "Staff"
,则应返回false。
I'm stuck re-re-reading the typescript enum documentation and I cluttered up a similar, but not duplicate question, by getting stuck in semantics just trying to make an enum type compile. 我被困在重新阅读打字稿枚举文档,并且由于试图仅仅为了枚举类型的编译而陷入语义中,我陷入了一个类似但并非重复的问题。 So, this question gets to the real issue I'm having: currentUser().level
is a string, but I need to match it to a value in the enumerated type and compare that to the enumerated value it should be greater than or equal to. 因此,这个问题涉及到我遇到的实际问题: currentUser().level
是一个字符串,但是我需要将其与枚举类型中的值进行匹配并将其与枚举值进行比较,该值应大于或等于至。
you can set the equivalent strnig to the enum types 您可以将等效的strnig设置为枚举类型
enum systemRoles {
Staff='Staff',
Manager='Manager',
DeptMgr='DeptMgr',
Executive='Executive',
Owner='Owner'
}
First off, you should store it as the enum if you can (there is no reason to do a string that I can think of). 首先,如果可以的话,应该将其存储为枚举(没有理由做一个我能想到的字符串)。
Second, as long as the names match exactly you can just index into the enum "object" so: 其次,只要名称完全匹配,您就可以索引到枚举“对象”,这样:
return systemRoles[currentUser().level] >= user_level
Will work. 将工作。 Indexing with a string will return the value, and indexing with a value will return the string. 用字符串索引将返回该值,而用值索引将返回该字符串。 And as always; 一如既往 make sure you validate the permissions on the backend! 确保您验证后端的权限! The UI cannot be counted on for true security. UI不能指望真正的安全。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.