简体   繁体   中英

Using *ngFor with JSON Angular2

I have a returned json object:

{
  "data": [
    {
      "type": "product",
      "id": "e0267f46-9721-48fc-8ee0-b554d82cfb52",
      "name": "fwefwefwef", 
...and so on...

I process it with this as part of my service:

export class MService {
...
     products.data.forEach(element => {
     let product = {
             name : element.name, 
             sku : element.sku, 
             description : element.description,
              category : element.relationships.categories.data[0].id,
             price: element.price[0].amount

            console.log(product);
          })
      });
  let product = MService
    });
  }
}

Which returns each object individually:

{
  "name": "Bombay Sapphire",
  "sku": "bomsaph",
  "description": "A great gin",
  "category": "46569361-13477074f952",
  "price": 1999
}

I have a model:

export class Prod{

    constructor(public name:string, public sku:string, public description:string, public category: string, public price:number){}

}

And a Component for which the *ngFor loop in the HTML returns needs to display what the API returns.

constructor (private mService: MService){ 

    products:Prod[] = [MService]
  }

HTML:

  <div *ngFor="let product of products"> 
      <div>{{product.name}} </div>
      <div>{{product.description}}</div>
      <div>{{product.sku}}</div>
    </div>

I am getting 'unused label' and 'expression expected' errors in the component.

Seems you want to extract some values from your JSON in objects and push each object to an array which you can iterate through. First of all, use interface instead of class, so your Prod would look like this:

export interface Prod{
  name:string;
  sku: string;
  description:string;
  category: string;
  price: number;
}

And instead of using forEach in your service, let's just use map to extract the properties you want, assign them to objects with Object.assign() , int the exact manner as you were using with forEach :

getData(){
  return this.http.get('src/data.json')
    .map(res => res.json().data.map((x:any) => 
       Object.assign({name:x.name,sku:x.sku,description:x.description,category:x.relationships.categories.data[0].id, price:x.price[0].amount})))
}

So now when we are receiving the data in the component, it's an array of type Prod , which you can use well in your template:

products: Prod[];

ngOnInit() {
  this.service.getData()
    .subscribe(data => {
      this.products = data;
    })
}

and template:

<div *ngFor="let product of products"> 
  <div>{{product.name}} </div>
  <div>{{product.description}}</div>
  <div>{{product.sku}}</div>
</div>

Here's a DEMO from where I got the complete JSON from your previous question: here

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