如何将JSON响应中的数据绑定到Dropdown List Angular2?

时间:2017-08-31 08:17:42

标签: json forms angular

我想将从Web服务器收到的数据绑定到我的前端应用程序中,但数据显示为未定义。数组本身正在获取可用对象的数量,数据绑定到组件而不是前端本身

这是我的模板:

form.component.html

    <label>Group ID</label>
      <div class="row" *ngIf="roles.length">
        <div class="col-md-4">
    <select [(ngModel)]="roles" name="group_id" class="form-control" [formControl]="complexForm.controls['group_id']" data-width='200px'>
    <option *ngFor="let role of roles" [value]="role.id">  
    {{role.name}}
    </option>
    </select>
        </div>
      </div>

数据看起来像这样,我应该根据值

显示名称
export class Group {
id: string;
name: string;
pwd_expiry_in_days: string;
}

我的组件看起来像这样,正在接收数据,并且我能够在组件内完美地记录数据

  public roles: Array<Group> = [];
  currentGroup : Group;


   private getGroups() : Observable<any> {
    console.log("In Groups");
    let _url = "myURL";
    let headers = new Headers();
    headers.append('X-User', sessionStorage.getItem('username'));
    headers.append('X-Token', sessionStorage.getItem('token'));
    headers.append('X-AccessTime', sessionStorage.getItem('AccessTime'));
    headers.append('Content-Type', 'application/json');
    let options = new RequestOptions({ headers: headers });

    return this.http.get(_url, options)
    .map(response => {
      var responseAsObject = response.json();
      console.log(responseAsObject); <--- Good response
      return responseAsObject;
    });
}


ngOnInit(){
  this.getGroups().subscribe(roles => { 
    this.roles = roles;
    console.log(this.roles); <--- Logs perfectly fine
  });
}

现在我有 this.roles 包含我要显示到前端的JSON对象数组,为什么它根据我在模板中的内容显示它们?

谢谢你!

2 个答案:

答案 0 :(得分:1)

试试这个:

public roles$: Observable<Array<Group>>;
currentGroup : Group;


private getGroups() : Observable<Group[]> {
    console.log("In Groups");
    let _url = "myURL";
    let headers = new Headers();
    headers.append('X-User', sessionStorage.getItem('username'));
    headers.append('X-Token', sessionStorage.getItem('token'));
    headers.append('X-AccessTime', sessionStorage.getItem('AccessTime'));
    headers.append('Content-Type', 'application/json');
    let options = new RequestOptions({ headers: headers });

    return this.http.get(_url, options)
               .map(response => response.json());
}


ngOnInit(){
  this.roles$ = this.getGroups()
                    .do(console.log);
}

...

<label>Group ID</label>
<div class="row" *ngIf="(roles$ | async)?.length">
  <div class="col-md-4">
    <select [(ngModel)]="roles" name="group_id" class="form-control" [formControl]="complexForm.controls['group_id']" data-width='200px'>
        <option *ngFor="let role of ($roles | async)" [value]="role.ID">{{role.NAME}}</option>
    </select>
  </div>
</div>

答案 1 :(得分:0)

您的控制台日志可能会在异步功能中收到后显示数据。 您在控制台日志中看到的内容很可能是在调用之后调用的。请你试试:

return new Promise<any>((resolve,reject) =>{
   this.http.get(_url, options)
   .map(response => {
      var responseAsObject = response.json();
      resolve(responseAsObject);
    });
    .toPromise()
    .catch(error =>{
      reject(error);
    })
})

ngOnInit(){
  this.getGroups().then(roles => { 
    this.roles = roles;
    console.log(this.roles);
  });
}