Joshua Szuslik
Joshua Szuslik

Reputation: 128

Displaying Angular 2 JSON Objects

I have an object being returned with a Promise.

My Object is structured like so:

export class ShoppingCart {
Cart_Items: [
    {
        Id: number,
        SKU: string,
        Link: string,
        ImageURL: string,
        Title: string,
        Description: string,
        Qty: number,
        Unit_Wt: number,
        Unit_Price: number,
        Sub_Total: number,
        Sub_Wt_Total: number,
        IsTaxExempt: boolean
    }
    ];
Shipping_Cost: number;
Taxes: number;
Discount: number;
Sub_Total: number;
Total_Wt: number;
Total: number;

}

I am using this in my component class:

display_cart: ShoppingCart;

constructor(private _shoppingCartService: ShoppingCartService) {}

getShoppingCart() {
    this._shoppingCartService.getShoppingCart().then(display_cart => this.display_cart = display_cart);
    // this.display_cart = this._shoppingCartService.getShoppingCart();
}
ngOnInit(){
    this.getShoppingCart();
}

In My service i am using this to get the data:

getShoppingCart() {
    return Promise.resolve(DISPLAY_CART);
}

The only thing I can use to display any of my data is {{ display_cart | json }} but that just returns my json. How do I extract the values and display the Cart_Items in a loop and the other variables where I need them?

Upvotes: 1

Views: 215

Answers (1)

Thierry Templier
Thierry Templier

Reputation: 202176

You could use something like that:

display_cart: ShoppingCart;

constructor(private _shoppingCartService: ShoppingCartService) {}

getShoppingCart() {
    this._shoppingCartService.getShoppingCart().then(
    display_cart => {
      this.display_cart = display_cart;
      this.items = display_cart.Cart_Items ;
    });
}

ngOnInit(){
    this.getShoppingCart();
}

And use items in the corresponding template:

<li *ngFor="#item of items">
  {{item.title}}
</li>

Upvotes: 1

Related Questions