首页 文章

使用* ngFor和JSON Angular2

提问于
浏览
0

我有一个返回的json对象:

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

作为我服务的一部分,我将其处理:

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

它分别返回每个对象:

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

我有一个模特:

export class Prod{

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

}

并且HTML中的* ngFor循环返回的Component需要显示API返回的内容 .

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>

我在组件中收到'unused label'和'expression expected'错误 .

1 回答

  • 1

    似乎您想从对象中的JSON中提取一些值,并将每个对象推送到可以迭代的数组中 . 首先,使用interface而不是class,所以 Prod 看起来像这样:

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

    而不是在你的服务中使用 forEach ,让我们只使用 map 来提取你想要的属性,用 Object.assign() 将它们分配给对象,与你使用 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})))
    }
    

    所以现在当我们在组件中接收数据时,它是一个 Prod 类型的数组,您可以在模板中很好地使用它:

    products: Prod[];
    
    ngOnInit() {
      this.service.getData()
        .subscribe(data => {
          this.products = data;
        })
    }
    

    和模板:

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

    Here's a DEMO 我从上一个问题中得到了完整的JSON: here

相关问题