简体   繁体   中英

ngFor not working angular5

I am trying to display some data from server in my component.

export class CommerceComponent implements OnInit {

     dealList;

    ngOnInit() {
         this.getDeals();
     }

    getDeals(){
    this.gatewayService.searchDeals(this.searchParams).subscribe(
      (data:any)=>{
        this.dealList = data.result;
        console.log("Deal list",this.dealList[0]);
      },
      (error)=>{
         console.log("Error getting deal list",error);
      }
    );
  }

Service

searchDeals(data){

        var fd = new FormData();
        fd.append('token',this.cookieService.get('token'));
        fd.append('search',data.keyword);

        return this.http.post(config.url+'hyperledger/queryByParams',fd);

    }

In html

<div class="deal1" *ngFor="let deal of dealList">
  {{deal.Deal.title}}
 </div>

But the list is not rendering, however, I am getting console.log("Deal list",this.dealList[0]); single object and this.dealList return array of objects

If you get the result in this.dealList[0] , you need also to iterate over [0] indexed item.

<div class="deal1" *ngFor="let deal of dealList[0]">
   {{deal.title}}
</div>

But your dealList is undefined, so accessing [0] will throw an exception. You need to initialize it as well

dealList = []

The title you wanted to display is located result[i].Deal.title Here is the image of your JSON response .

在此处输入图片说明

<div class="deal1" *ngFor="let deal of dealList">
    {{deal.Deal.title}}
</div>

You are assigning the response.results object to the dealList. All your code is okay except for the one in template.

That is ->

this.dealList = data.result;

Here is how data.result looks:

在此处输入图片说明

I think it should be:

 <div class="deal1" *ngFor="let deal of dealList"> {{deal.Deal.title}} </div> 

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