更新可观察到的“ roles [0]未定义”

时间:2019-06-21 09:25:10

标签: angular angular6

我有此映射用户* --------------- *角色

知道了

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

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

我想更新一个用户。波纹管是必需的文件:

modify-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);
      });
  }

}

user.service.ts中的函数updateUsera

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

更新成功完成。 但是,从list-users.components.htmlmodify-user.component.ts导航时,我有两个错误:

  • 第一个问题:调养的角色为假。真正的作用是 ADMIN_ROLE,但这里有USER_ROLE(它通常显示第一个 列表中的角色)。
  • 第二个问题:当我从用户列表中选择一个用户进行修改时(从列表用户导航以修改所选用户时),我得到了this error

您能帮我解决这个问题吗? 预先感谢。

1 个答案:

答案 0 :(得分:0)

您必须定义角色[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