开发者问题收集

TypeError:无法读取 angular 4 中未定义的属性“length”

2018-04-09
2185

TypeError:无法读取 angular 4 中未定义的属性“length”

这是代码 export class UserComponent implements OnInit{

  roles:IUserRole[];
  sourseRoles: SelectedItem[];
  selectedRole:any;

BindRoles() {
    this.sourseRoles= [];
    this.sourseRoles.push({ label: "Assign Role", value: null });
    if (this.roles.length > 0) {
      for (let role of this.roles) {
        this.sourseRoles.push({ label: role.Title, value: role.UserRoleId })enter image description here
      }
    }
  }
----------

这是代码

this.appServiceManager.libGet("Role") .subscribe((role: any) => { this.selectedRole= [];

           this.selectedRole = role;
           this.sourseRoles.push({ label: this.selectedRole.Title, value: this.selectedRole.UserRoleId })
         },
         (error: any) => {
           this.msgs = [];

           this.msgs.push({ severity: 'error', summary: 'Error Message', detail: error });
         });
----------
<label for="password">User Role</label>
 <p-dropdown name="Title" #Title="ngModel" required (click)="BindRoles()" 

 [(ngModel)]="selectedRole" id="dropdown" [options]="sourseRoles"

 [autoWidth]="false"></p-dropdown>

 <div *ngIf="registerForm.submitted && !Title.valid" class="help-block">Role 
 Information is required</div>

----------
2个回答
export class UserComponent implements OnInit {
    roles: IUserRole[] = [];     <======= Initialize it =========>
    sourseRoles: SelectedItem[]; <======= Declaration was incorrect =========>
    selectedRole: any;

    BindRoles() {
      if (this.roles.length > 0) {
        for (let role of this.roles) {
          this.sourseRoles.push({ label: role.Title, value: role.UserRoleId })
        }
      }
    }
}
Anshuman Jaiswal
2018-04-09

我在TS代码中看不到这一点:

254548954

我看到了您的角色和SelectedRole

Phil Boyd
2018-04-09