如何在Angular 6中的服务调用中读取嵌套的JSON对象

问题描述 投票:1回答:1

我在如下所示的API端点处有一个嵌套的JSON对象

[
  {
    "id": "order-1",
    "recipient": {
      "name": "John Smith",
      "email": "[email protected]"
    },
    "created_at": "2018-11-01T09:42:30Z",
    "items": [
      {
        "id": "item-1",
        "name": "Supersoaker 3000",
        "quantity": 2,
        "total_price": {
          "currency": "EUR",
          "amount": "24.33"
        }
      },
      {
        "id": "item-2",
        "name": "Nunchucks XXX",
        "quantity": 1,
        "total_price": {
          "currency": "EUR",
          "amount": "39.99"
        }
      }
    ],
    "delivery": {
      "courier": "DPP",
      "method": "Express"
    },
    "charge_customer": {
      "currency": "EUR",
      "total_price": "18.00"
    }
  }
]

我正在尝试在order-results-service.ts中调用服务,以从api中获取嵌套对象,如下所示:

  getOrderResult(): Observable <IOrder[]>{
    this.getSubmitCriteria();
    return this.http.get<serverData>(this.url, this.submitCriteria)
      .pipe(map(res => <IOrder[]>res.orders),
        catchError(this.handleError('getOrderResult',[])));

  }

我在下面的interface.ts中定义IOrder []接口:

interface Recepient {
    name?: string;
    email?: string;
}

interface Delivery {
    courier?: string;
    method?: string;

}

interface totalPrice {
    currency?: string;
    total_price?: number;
}
interface Items {
    id?: string;
    name?: string;
}

export interface IOrder {
  recepient: Recepient[];
  totalPrice: totalPrice[];
  createdDate: string;
  items: Items[];
  deliveryDetails: Delivery[]; 
}

并且在order.component.ts中,我像下面这样调用服务:

 ngOnInit() {
    this.loadData();

  }

  loadData(){
      this.orderResultsService.getOrderResult().subscribe((data: IOrder[]) =>   {        

          this.orders = data;

      }), error => {
        this.errormsgs = [{ severity: 'error', detail: 'error'}];
      }
  }

但是当我订阅可观察对象时,我无法从组件中的JSON对象获取值。我正在获取服务中的价值。我还需要有关如何在前端显示数据对象的帮助。我尝试从PrimeNG使用,也使用了* ngFor,例如下面的html:

<div *ngFor="let order of orders">
    <div *ngFor="let x of order.recipient">
        <strong>Recipient Name:</strong>{{x.name}}
        <strong>Recipient Email Address:</strong>{{x.email}}
    </div>
    <div *ngFor="let y of order.items">
        <strong>Item Id:</strong>{{y.id}}
        <strong>Item Name:</strong>{{y.name}}
    </div>
    <div>
        <strong>Time when order was made:</strong>{{order.created_at}}
    </div>
    <div *ngFor="let z of order.delivery">
        <strong>Courier Name:</strong>{{z.courier}}
        <strong>Courier Method:</strong>{{z.method}}
    </div>
    <div *ngFor="let p of order.charge_customer; let i =index">
        <strong>Total Price of the Order:</strong>{{p.amount}}{{p.currency}}
    </div>
</div>

但是我无法在前端或服务中获取这些值。我在这里错了吗?

json object service nested angular6
1个回答
0
投票

使用此来提取值。范例-data [“ recipient”]。name和data [“ recipient”]。email,然后将其放入变量中。像此示例一样,仅尝试提取数据。

© www.soinside.com 2019 - 2024. All rights reserved.