0

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!

4
  • Try using the async pipe in the for-loop let role of roles|async Commented Aug 31, 2017 at 8:20
  • Gives an error: ERROR Error: InvalidPipeArgument: '[object Object],[object Object]' for pipe 'AsyncPipe' Commented Aug 31, 2017 at 8:21
  • Try to wrap your for loop with an *ngIf=roles. <option *ngIf="roles" *ngFor="let role of roles" [value]="role.id"> {{role.name}} </option> or on the outer element <select *ngIf="roles" ...... </select> (without using the async pipe) Commented Aug 31, 2017 at 8:24
  • Also, have a look at this one: stackoverflow.com/questions/44089350/…. they use the async pipe on both the select element and the option-element loop Commented Aug 31, 2017 at 8:33

2 Answers 2

1

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>
Sign up to request clarification or add additional context in comments.

16 Comments

Type 'Observable<Group[]>' is not assignable to type 'Group[]'. Property 'includes' is missing in type 'Observable<Group[]>' - In OnInit
Are you sure, that you have changed type of roles$?
you were right, I fixed it however the drop down list is empty. Before it would display 2 undefined objects
Great, one step by another ;-) In your console.logs, id and name values are set, right? Is it possible to post the log?
the naming convention to upper case worked because the data members were being retrieved in upper case from the database. So the modification to fix it was to change my model to upper case as you suggested. Thank you :)
|
0

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

2 Comments

Isn't it better to use Observables than Promises?
Yes, indeed observables have more functionality, but if you don't need that functionality I see no point in using one.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.