来自对象?

时间:2017-07-06 10:30:27

标签: angular ionic-framework ionic2

我使用的是Ionic 2 / Angular,但我意识到ngFor功能无法读取对象。此外,我只有在{ "48131": { "code":"D40905", "name":"ДАМСКА ПЛЕТЕНА БЛУЗА КЪС РЪКАВ ЩАМПА REASON", "price":"18.99", "size":"STANDART", "qty":"1" }, "49410": { "code":"D41821", "name":"ДАМСКА БЛУЗА ТРИКО", "price":"44.99", "size":"M", "qty":"4" } } 不为空时才需要显示它。

对象:

<ion-row *ngFor="let p of cart">
    <ion-col col-3>
        <div><img src="http://example.com/products/small/{{p.code}}-1.jpg" /></div>
    </ion-col>
    <ion-col col-9>
        <ion-row>
            <ion-col col-12>
                <div>{{p.name}}</div>
            </ion-col>
        </ion-row>
        <ion-row>
            <ion-col col-12>
                <div>{{p.qty}} бр ({{p.size}} размер) x <b>{{p.price}} лв</b></div>
            </ion-col>
        </ion-row>
        <ion-row>
            <ion-col col-12>
                <div (click)="deleteCart({{p.id}})">Изтрий <ion-icon name='trash' item-start color="danger"></ion-icon></div>
            </ion-col>
        </ion-row>
    </ion-col>
</ion-row>

HTML:

  public static final String DATETIME_PATTERN="yyyy/MM/dd - HH:mm:ss";

有人可以帮我吗?我尝试了很多东西......

3 个答案:

答案 0 :(得分:2)

您可以将Pipe用于此目的

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'object' 
})
export class ObjectForPipe implements PipeTransform {
    transform(value: any, arg1): any {
        return typeof value!=='object' ? [] : Object.keys(value);
    }
}

在AppModule中 - &gt; @NgModule

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { ObjectForPipe } from 'path-to-pipe/object.pipe.ts';

@NgModule({
  declarations: [
    AppComponent,
    ObjectForPipe
  ],
  imports: [
    ...
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

HTML

<div *ngFor="let key of objs | object">

从版本6.1开始,Angular引入了keyValue Pipe:

<div *ngFor="let item of map | keyvalue">
   {{item.key}}:{{item.value}}
</div>

答案 1 :(得分:1)

你的卡片json不是数组。它应该是

[
    "48131": {
        "code":"D40905",
        "name":"ДАМСКА ПЛЕТЕНА БЛУЗА КЪС РЪКАВ ЩАМПА REASON",
        "price":"18.99",
        "size":"STANDART",
        "qty":"1"
    },
    "49410": {
        "code":"D41821",
        "name":"ДАМСКА БЛУЗА ТРИКО",
        "price":"44.99",
        "size":"M",
        "qty":"4"
    }
]

答案 2 :(得分:-1)

根据此链接将您的json对象转换为数组

https://stackoverflow.com/a/37667589/2013245

然后你应该没事。