简体   繁体   中英

Bind API Data in Angular?

I am trying to bind Data which is coming from API, Data is showing in the.network but When I am trying to bind data it is giving me an error -

Cannot find a differ supporting object
function'. NgFor only supports binding to Iterables such as Arrays.

API Data in Network

 [{deliveryid: 0, frequency: "", ContactName: "Aa", Email: "aa@we.com",…},…]
     
//While expanding the response

{deliveryid: 0, frequency: "", ContactName: "Aa", Email: "aa@we.com"}

.TS

  public MyDigestEmailIdPrint = [];
  DigestEmailIdPrint() {
    var postData = {
    clientid: localStorage.getItem("storageselectedclient"),
  };

    this.article.DigestEmailIdPrint(postData).subscribe(
    (res) => { 
    if (res.message != "No Record Found") {
       this.MyDigestEmailIdPrint.push(res);
    }
  },
  (err) => {
    console.log(err);
  }
);

}

.HTML

<tbody>
  <tr *ngFor="let details of MyDigestEmailIdPrint">
    <td> {{details.ContactName}}</td>
    <td> {{details.Email}}</td>
    <td> {{details.frequency}}</td>
    <td><input type="checkbox"></td>
  </tr>

</tbody> 

DigestEmailIdPrint is a function and doesn't return anything. Maybe you should use MyDigestEmailIdPrint in the ngFor but as pointed out in the comment, the data you get from the backend is not an array.

you can fix it like this:

if (res.message != "No Record Found") {
    // use the spread syntax to create a new array and trigger change detection
    this.MyDigestEmailIdPrint = [...res.result];
}

I would suggest you to check the res type. It seems it must be an object and thats what the error is pointing to NgFor only supports binding to Iterables such as Arrays.

The error is not only linked to this, the question is when are you calling the API and does the view load till that time?

Solution 1: If your response in the component is of different type, you can covert it to array.

Solution 2: Check when the data is getting loaded into the view. You should know the lifecycle hooks to get the data at correct time to get things in component.

Solution 3:


if (res.message != "No Record Found") {
    // node need to push data to MyDigestEmailIdPrint
    // this.MyDigestEmailIdPrint.push(res); // add the data in the array
    this.MyDigestEmailIdPrint = res; // if res is an array it is fine to assign
}

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