简体   繁体   中英

Can't bind data from web api to select option in Angular

I am trying to bind some data to a select option in Angular 6, I am using *NgFor for this: The Json data structure is as follows:

{  
   "addresses":[  
      {  
         "address":"xxxxxxx",
         "address_line1":"None",
         "address_line2":"None",
         "address_line3":"",
         "billing":false,
         "id":79,
         "name":"xxxxx",
         "phone_number":null,
         "postal_code":"xxxxx",
         "town":"xxxxx"
      },
   ]
}

So to bind this into my select option I am doing:

<option value="null" disabled="true" [selected]="true">Select your option</option>
<option *ngFor="let item of address" [value]="item">
    {{item.address}}
</option>

Ts file to get data:

customerAddress = []; 

private getCustomerAddress() {
    this.service.getCustomerAddress(this.customer_id).subscribe((data) => {
      console.log('Result - ', data);
      console.log('Customer address data is received');
      this.customerAddress = data;
    })
  }

Service linked to this:

  getCustomerAddress(customerId): Observable<any> {
    return this.http.get<any>(this.customerAddressApiUrl + "/" + customerId)
      .pipe(
        catchError(this.handleError)
      );
  }

There is no data being displayed in the select option? But data is fine in the console.log.

This is the correct way to do it:

<option *ngFor="let item of customerAddress.addresses" [value]="item">
    {{item.address}}
</option>

您正在浏览的数组的名称是customerAddress而不是adresses

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