首页 > 解决方案 > 如何确定要在前端显示的角色 - Angular 7

问题描述

我正在开发一个使用 Angular-7 作为前端的 Web 应用程序。我在复选框上显示用户角色,您可以选择多个角色。

用户.component.ts

import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { ApiService } from '../../../shared/services/api.service';
import { SnotifyService } from 'ng-snotify';
import { Router, ActivatedRoute } from '@angular/router';
import { TokenService } from '../../../shared/services/token.service';
import { RolesCheckService } from 'src/app/shared/services/roles-check.service';

@Component({
  selector: 'app-users',
  templateUrl: './users.component.html',
  styleUrls: ['./users.component.scss']
})
export class UsersComponent implements OnInit {

users = null;     //Store Users Data
roles = null;     //Store all roles Data
clients = null;

public error = {
  'role' : null,
  'email' : null,
  'client_id' : null,
  'first_name' : null,
  'last_name' : null,
  'password' : null
};

role = null;
User = 'User';

data = {          //User Update Data
 "id" : null,
 "first_name" : null,
 "last_name" : null,
 "client_id" : null,
 "role" : []
}

form = {         //New User add Data
  'first_name' : null,
  'last_name' : null,
  'email' : null,
  'client_id' : null,
  'password' : null,
  'password_confirmation' : null,
  'role' : []
}

headers = {     //Token for API Authorization
  'Authorization' : this.token.get(),
  'X-Requested-With' : 'XMLHttpRequest'
}

isSuperAdmin = false;

constructor(private roleManage : RolesCheckService , private route : ActivatedRoute, private pg:   NgbPaginationConfig, private token : TokenService, private http : HttpClient, private router :   Router,private api : ApiService, private notify : SnotifyService) {
 pg.boundaryLinks = true;
 pg.rotate = true;
}

ngOnInit() {
  console.log('isSuperAdmin: ' + this.roleManage.isSuperAdmin);
  this.isSuperAdmin = this.roleManage.isSuperAdmin;
  if(!this.isSuperAdmin){
    this.notify.error("Permission Denied");
    this.router.navigateByUrl("/home");
  }
  this.route.queryParams.subscribe(params => {
    if(params['role']){
      this.role = params['role'];
      this.User = this.role;

  } else {
    this.User = 'User';
    this.role = '';
  }
})
this.notify.clear();
this.notify.info("Loading...", {timeout: 0});

if(this.keyword) {
  this.api.get('users?search=' + this.keyword + '&page=' + this.pagination.page + '&sort=' + this.sortData.col + '&order=' + this.sortData.order + '&role=' + this.role, this.headers).subscribe(
    data => this.datahandler(data),
    error => { this.notify.clear(); console.log(error); this.notify.error(error.error.message); }
  );
} else {
  this.api.get('users?page=' + this.pagination.page + '&sort=' + this.sortData.col + '&order=' + this.sortData.order + '&role=' + this.role, this.headers).subscribe(
    data => this.datahandler(data),
    error => { console.log(error); this.notify.error(error.error.message); }
  );
}
this.api.get('role', this.headers).subscribe(
  data => { console.log(data); this.roles=data; },
  error => { console.log(error); this.notify.clear(); this.notify.error(error.error.message); }
);
this.api.get('users/clientall', this.headers).subscribe(
  data => this.clients = data,
  error => { this.notify.error(error.error.message) }
);
}


datahandler(data){
 console.log(data.data);
 this.notify.clear();
 this.users = data.data;
 this.pagination.max = data.total;
}

//New User add Handling
add(){
  this.notify.clear();
  this.form.first_name = null;
  this.form.last_name = null;
  this.form.email = null;
  this.form.password = null;
  this.form.password_confirmation = null;
  this.form.role = [];

  var modal = document.getElementById('addModal');
  modal.style.display = "block";
}

checkboxAdd(event){
  if(event.srcElement.checked){
  this.form.role.push(event.srcElement.name);
} else {
  var index =this.form.role.indexOf(event.srcElement.name);
  this.form.role.splice(index, index+1);
}
  console.log(this.form.role);
}

addModalSubmit(){
  this.notify.clear();
  this.notify.info("Wait...", {timeout: 0});
  this.api.post('users', this.form, this.headers).subscribe(
    data => {
      this.notify.clear();
      this.notify.info("User Added Successfully", {timeout: 2000});
      this.ngOnInit();
      this.closeAddModal();
   },
     error => { this.notify.clear(); this.error = error.error.errors; }
  );
 }

closeAddModal(){
 this.error = {
  'role' : null,
  'email' : null,
  'client_id' : null,
  'first_name' : null,
  'last_name' : null,
  'password' : null
};
  var modal = document.getElementById('addModal');
  modal.style.display = "none";
 }
}

角色以数组的形式出现

'角色': []

user.component.html

<div class="col-xs-4">
  <a (click)='add()' class="btn btn-block btn-success" style="margin-right: 15px;"><i class="fa fa-plus"></i> Add New {{ User }}</a>
</div>

<div id="addModal" class="modal" style="background-color: rgb(0,0,0); background-color: rgba(0,0,0,0.4);">
  <div class="modal-dialog" role="document">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title">Add New {{ User }}</h5>
          <button type="button" class="close" (click)='closeAddModal()'>
            <span aria-hidden="true">&times;</span>
          </button>
        </div>
        <div class="modal-body">
          <form #editUserForm=ngForm>
              <div class="form-group">
                <label for="name">First Name</label>
                <input type="name" name="first_name" id="inputName" class="form-control" placeholder="First Name" [(ngModel)]="form.first_name" required>
              </div>
              <div class="form-group">
                  <label for="name">Last Name</label>
                  <input type="name" name="last_name" id="inputName" class="form-control" placeholder="Last Name" [(ngModel)]="form.last_name" required>
                </div>
              <div class="form-group">
                  <label for="name">Email</label>
                  <input type="email" name="email" id="inputEmail" class="form-control" placeholder="example@email.com" required [(ngModel)]="form.email">
                </div>
                <div class="form-group">
                    <label for="name">Role</label>
                    <div *ngFor="let role of roles">
                        <input type="checkbox" name="{{ role.name }}" value="{{ role.name }}" (change)="checkboxAdd($event)"> {{ role.name }}
                    </div>
                </div>
          </form>

        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-primary" (click)='addModalSubmit()' [disabled]="!editUserForm.valid">Save changes</button>
          <button type="button" class="btn btn-secondary" (click)='closeAddModal()'>Close</button>
        </div>
      </div>
    </div>
</div>

数据库中大约有六个用户角色,还可以添加更多。在复选框中,我只想显示这些角色供用户查看和选择:教师和学生,使用 role.name。属性是名称。我如何实现这一目标?

标签: angular

解决方案


您可以在您的打字稿文件中使用一个 getter 以在您的 ngFor 中使用它已经过滤掉了所有不需要的项目,或者您可以使用 ngFor 的自定义管道仅过滤您想要显示的项目,请参阅this answer。使用管道,您可以按名称过滤项目。


推荐阅读