Got error when updating an observable "roles[0] is undefined"

Viewed 96

I have this mapping User * --------------- * Role

Knowing that

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

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

I want to update a user. Bellow are the required files:

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>

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

}

And the function updateUsera inside user.service.ts is:

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

The update is done with success. But, I have two bugs when navigate from the list-users.components.html to modify-user.component.ts which are :

  • First issue: The recuperated role is false. The real role is ADMIN_ROLE, but here I have USER_ROLE( It usually shows the first role of the list).
  • Second issue: I got this error when I select a user from the list of users to modify it (when navigate from list users to modify the selected user).

Could you please help me solving that issue ?. Thanks in advance.

1 Answers

You have to define roles[0]. I don't know why using the first index, because that give you usually the first value which is wrong as you described. So try rol: [this.selectedRoleUserCompare.num, Validators.required] inside this.editForm = this.formBuilder.group.

Then replace that on your html file:

<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

Related