Angular(TypeScript):如何按角色条件过滤数组中的按钮项
解决方案
你不能直接在数组字面量里插入条件判断语句,这会违反TypeScript的语法规则,以下两种方法可以解决你的问题:
方法一:使用数组过滤(filter)
先定义基础的按钮数组,再根据当前角色过滤掉不需要的按钮:
const baseButtons = [ { DisplayName: "Create User", Target: "./createuser" }, { DisplayName: "Load Products", Target: "./getproducts/all" } ]; this.getButtons = { Buttons: baseButtons.filter(button => { // 当角色为WL_H3G时,排除Create User按钮 if (this.role === 'WL_H3G') { return button.DisplayName !== 'Create User'; } // 其他角色保留所有按钮 return true; }) };
方法二:使用扩展运算符+三元表达式
通过三元表达式条件性地添加数组元素,语法更简洁:
this.getButtons = { Buttons: [ // 仅当角色不是WL_H3G时,才添加Create User按钮 ...(this.role !== 'WL_H3G' ? [{ DisplayName: "Create User", Target: "./createuser" }] : []), // 始终保留Load Products按钮 { DisplayName: "Load Products", Target: "./getproducts/all" } ] };
这两种方法都能避开直接在数组内写条件语句导致的编译错误,同时满足你的角色权限需求。
内容的提问来源于stack exchange,提问作者nik
相关产品推荐
相关产品推荐

