【问题标题】:enable and desable all elements in one component/HTML启用和禁用一个组件/HTML 中的所有元素
【发布时间】:2021-01-23 23:00:36
【问题描述】:

我是一名初学者开发人员,我正在尝试验证一些用户的权限访问,为此我构建了一个服务,该服务可以根据他们启用的视图来验证用户角色权限是否返回真或假。现在我有消息“欢迎”和“你无权访问”来测试它;现在我需要做的是启用所有页面/组件,然后启用一些功能(表单、按钮、表格视图等)或禁用所有组件,以防用户无权访问。我需要该用户可以看到该页面,但只有他拥有权限才能使用它。有人知道我该怎么做吗?

 export class WriteComponent implements OnInit {

  constructor(public userMngmtService: UserMngmtRolesService, public router: Router, public routeComponent : ActivatedRoute,public toaster: ToastrService) {

  }

  ngOnInit(){
    // this.route = this.router.url;
    // console.log('lelelel',this.route)
    var route = "write";
    var role = localStorage.getItem('roleId');
    this.userMngmtService.validatepermissions(role,route).subscribe(
      (canAccess: any) => {
        console.log('canAccess', canAccess);
        if(canAccess == true){

          this.toaster.success("Welcome!")
        }else{
          if(canAccess == false){
            this.toaster.error("U don't have permissions to access!")
          }
        }
      });
  }

}

【问题讨论】:

    标签: html angular components


    【解决方案1】:

    你可以在你的类中声明一个布尔属性,例如canAccess 然后在 if/else 语句中为该属性分配 true 或 false:

     export class WriteComponent implements OnInit {
    
       canAccess: boolean;
    
       constructor(public userMngmtService: UserMngmtRolesService, public router: Router, public routeComponent : ActivatedRoute,public toaster: ToastrService) {
    
       }
    
       ngOnInit(){
         var route = "write";
         var role = localStorage.getItem('roleId');
         this.userMngmtService.validatepermissions(role,route).subscribe(
           (canAccess: any) => {
             console.log('canAccess', canAccess);
             if(canAccess == true){
               this.canAccess = true; 
             }else{
               if(canAccess == false){
                 this.canAccess = false;
               }
             }
           });
       }
    }
    

    然后您可以在 html 中使用此属性和 *ngIf 来显示/不显示特定元素:

    <div *ngIf="canAccess; else noAccess">
      Welcome
      <!-- put your forms, buttons, tables etc. in here -->
    </div>
    
    <ng-template #noAccess>
     <div>You do not have permission to view this</div>
    </ng-template>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-07-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多