Adjoa Wadee
Adjoa Wadee

Reputation: 109

Parse a JSON response Angular 2

Does anyone know how I can parse a JSON response into a structure like this?

   [
  {
    "iD": 2,
    "OrderList": [
      {
        "bidPrice": 0,
        "iD": 0,
        "name": "Name",
        "price": 10,
        "resteurant": "Restaurant"
      },
      {
        "bidPrice": 0,
        "iD": 0,
        "name": "Something",
        "price": 20,
        "resteurant": "La Place"
      }
],
    "owner": "Tom"
  }
]

I used json2ts to create these two structures:

  import {OrderList} from "./OrderList.ts";
import {Injectable} from  "@angular/core";

@Injectable()

export interface OrderBasket {
    iD: number;
    OrderList: OrderList[];
    owner: string;
}

and

import {Injectable} from  "@angular/core";

@Injectable()
export interface OrderList {
    bidPrice: number;
    iD: number;
    name: string;
    price: number;
    resteurant: string;
}

I make a call to the server and subscribe, but i cannot get this structure. Can anyone help ?

Upvotes: 2

Views: 29535

Answers (1)

Thierry Templier
Thierry Templier

Reputation: 202176

I think that you could try the following:

this.http.get('http://...')
  .map(res => <OrderBasket[]>res.json())
  .subscribe(data => {
    // data corresponds to a list of OrderBasket
  });

You need to be aware of implications of casting with TypeScript:

Otherwise, I don't understand why you use the Injectable decorator on your interfaces.

Upvotes: 9

Related Questions