DarioN1
DarioN1

Reputation: 2552

Angular2 / Typescript : render json object with unknow structure in component

I need to render a json object that is the output of a webapi call on a component.

The problem is that this response has not a fixed structure, it can change depending on the webapi execution.

Sometimes it can be a simple array, other time an array of object etc...

How can I render it without knowing the output structure ?

For who comes from PHP development, I need like something like print_r function...

Thanks Regards

Upvotes: 1

Views: 448

Answers (1)

Leon Radley
Leon Radley

Reputation: 7672

It depends on how you want to render it.

To debug you can use the json pipe

{{data | json}}

Otherwise you could check if the returned response is an array or an object and render it based on that.

if (Array.isArray(data)) {
  // render as array
} else {
  // render as something else
}

I would probably try to normalize the datastructure that is returned from an angular service so that it's always an array of objects, and then based on if the objects contain different keys render it differently.

Upvotes: 3

Related Questions