简体   繁体   中英

How to bind data from JSON response into Dropdown List Angular2?

I want to bind data that I received from my web server into my front end application however the data is showing up as undefined. The array itself is taking the number of objects available, and data is binding to the component but not the front end itself

Here is my Template:

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>

The data looks like this, I'm supposed to display the name based on the value

export class Group {
id: string;
name: string;
pwd_expiry_in_days: string;
}

My component looks like this, data is being received and I'm able to log the data perfectly within the component

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

Now that I have this.roles containing my array of JSON objects to display to the front end, why is it failing to display them based on what I have in my template?

thank you!

Try this:

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>

Your console logs may show data after they've been received in an async function. What you see in the console log most probably is called after. Please could you try :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM