Ошибка при обновлении наблюдаемого «Роли [0] не определены» - PullRequest
1 голос
/ 21 июня 2019

У меня есть это отображение Пользователь * --------------- * Роль

Зная, что

export class User
{
    id: number;
    name: string;
    roles: Role[];
}

export class Role
{
    id: number;
    name: string;
}

Я хочу обновить пользователя. Ниже приведены необходимые файлы:

модификация-user.component.html

<form [formGroup]="editForm" (ngSubmit)="onSubmit()">
        <div class="form-group">
            <label for="name">Role</label>
            <select (change)="onChangeRoleName($event)" 
               class="form-control select2" style="width: 100%;">
                <option *ngFor="let role of rolees" [ngValue]="role" [selected]="selected">{{role.name}}</option>
              </select>
        </div>

        <div class="form-group">
            <label for="name">Name</label>
            <input type="text" formControlName="name" placeholder="Name" name="name" class="form-control" id="name">
        </div>

        <button class="btn btn-success">Update</button>
    </form>

И user-modify.component.html

export class ModifyUserComponent implements OnInit
{

  editForm: FormGroup;
  submitted = false;
  private selectedRole;
  users: Observable<User[]>;
  libelleRole: string;
  usrId: String;
  selectedRoleUserCompare = {num: localStorage.getItem("selectedRoleId"), name: localStorage.getItem("selectedRoleName")}
  roleName: String;
  rolees:Array<Object> =
  [
      {num: 1, name: "ROLE_USER"},
      {num: 2, name: "ROLE_PM"},
      {num: 3, name: "ROLE_ADMIN"}
  ];

  compareFn(a, b)
  {
    console.log(a, b, a && b && a.num == b.num);
    return a && b && a.num == b.num;
  }

  constructor(private formBuilder: FormBuilder, private router: Router, private userService: UserService) {}

  ngOnInit()
  {
      this.roleName = localStorage.getItem("roleLibelle");

      let userId = localStorage.getItem("editUserId");
      this.usrId = localStorage.getItem("editUserId");
      if(!userId)
      {
          alert("Invalid action.")
          this.router.navigate(['users-list']);
          return;
      }

      this.userService.getUserEntityId(+userId).map(se=> se.roles[0].name).subscribe((response)=>
      {
          this.libelleRole = response;
          localStorage.setItem("roleLibelle", this.libelleRole);
      });


      this.editForm = this.formBuilder.group
      ({
          id: [],
          name: ['', Validators.required],
          username: ['', Validators.required],
          email: ['', Validators.required],
          password: ['', Validators.required],
          age: ['', Validators.required],
          active: ['false']
      });

      this.userService.getUserId(+userId).subscribe( data =>
      {
          this.userService.getUserEntityId(+userId).map(se=> se.roles[0].name).subscribe(name=>
          {
              this.libelleRole = name;
              this.editForm.setValue(data);
          });
      });
  }

  onChangeRoleName($event)
  {
      this.selectedRole = $event.target.options[$event.target.options.selectedIndex].text;
  }

  newUser(): void
  {
      this.submitted = false;
  }

  onSubmit()
  {
      this.userService.updateUsera(this.editForm.value, this.selectedRole).subscribe(data => 
      {
          this.router.navigate(['users-list']);
      },
      error =>
      {
          alert(error);
      });
  }

}

А функция updateUsera внутри user.service.ts равна :

updateUsera(user: User, roleName: string)
    {
        let userId = localStorage.getItem("editUserId");
        return this.http.put(`${this.baseUrl}/users` + '/' + userId  + '/' + roleName, user);
    }

Обновление выполнено успешно. Но у меня есть две ошибки при переходе от list-users.components.html к modify-user.component.ts:

  • Первая проблема: восстановленная роль ложная. Настоящая роль ADMIN_ROLE, но вот у меня USER_ROLE (обычно показывает первый Роль списка).
  • Вторая проблема: я получил эту ошибку , когда я выбираю пользователя из списка пользователей, чтобы изменить его (при переходе из списка пользователей, чтобы изменить выбранного пользователя).

Не могли бы вы помочь мне решить эту проблему? Заранее спасибо.

1 Ответ

0 голосов
/ 24 июня 2019

Вы должны определить роли [0].Я не знаю, зачем использовать первый индекс, потому что он обычно дает вам первое значение, которое неверно, как вы описали.Так что попробуйте rol: [this.selectedRoleUserCompare.num, Validators.required] внутри this.editForm = this.formBuilder.group.

Затем замените это в своем html-файле:

<div class="form-group">
              <label for="name">Role</label>
              <select (change)="onChangeRoleName($event)" class="form-control select2" style="width: 100%;" formControlName="rol">
                  <option *ngFor="let role of roles" [ngValue]="role.num">{{role.name}}</option>
              </select>
            </div>

HTH

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...