将http obervable响应转换为ngFor支持的数组

时间:2018-03-01 06:16:55

标签: typescript observable angular5

我正在尝试根据API响应动态加载选择选项,对于http请求,我在Angular5中使用了obervables。

但它将响应解析为select选项会抛出错误。

Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays




ngOnInit() {  

    this.roles = this.roleService.getRoles();
    console.log("Roles Are here",this.roles);
}
}

html

 <select id="userrole" class="form-control " name="userrole" formControlName="userrole" data-live-search="true">
          <option *ngFor="let p of roles" value={{p[0]}}>{{p[1]}}</option>
        </select>

在这里检查Plunkr Code

1 个答案:

答案 0 :(得分:1)

以下工作:

this.roleService.getRoles().subscribe(roles => {
  this.roles = roles;
});

您可以访问subscribe

中的回复数据

更新了HTML:

<div>
  <h2>Hello {{name}}</h2>
</div>
<div class="container row">
  <div class="col-md-6">
    <form [formGroup]="userRegform" novalidate>
      <fieldset class="form-group">
        <select id="userrole" class="form-control " name="userrole" formControlName="userrole" data-live-search="true">
          <option *ngFor="let p of roles" [value]="p['ROLE_ID']">{{p['ROLE']}}</option>
        </select>
      </fieldset>
      <fieldset class="form-group">
        <select class="form-control selectpicker" data-live-search="true">
          <option data-tokens="ketchup mustard">Hot Dog, Fries and a Soda</option>
          <option data-tokens="mustard">Burger, Shake and a Smile</option>
          <option data-tokens="frosting">Sugar, Spice and all things nice</option>
        </select>
      </fieldset>
    </form>
  </div>
</div>