Reputation: 180
I am learning and get always struggle with same problems. I want to load a list from my json file. The problem is that the json is not like this:
[{ "id":"1"},{ "id":"2"}]
Instead of this I have more complex lists like:
[{"data":[{"id":"1"},{"id":"2"}]}]
and even more rows inside. If I do subscribe in angular like this:
getCustomersList()
.subscribe(
data => {
this.consolelist = data[0].data;
});
I always get output of whole file and have to do ngfor
in template, or even sometimes ngfor
in ngfor
. Isn't it possible to build a new array like new = []; and read only data[0].data inside? How is this handled? Is my thinking wrong and do I always have to build this way, with ngFor
in the template?
Are there any tutorials which explain it, or something like this?
Upvotes: 1
Views: 61
Reputation: 4582
You can use .forEach()
, .map()
, or any other Array function for this.
You should not have to rely on your template for excessive processing of your data.
You can start with an empty array with []
as well, as you indicated. For instance, if your data comes in like this:
[{
"data":[
{"id":"1", "name": "Tom"},
{"id":"2", "name": "Dick"},
{"id":"3", "name": "Harry"},
{"id":"4", "name": "Rumplestiltskin"}
]
}]
You can do this, using .forEach()
:
getCustomersList()
.subscribe(
data => {
this.consolelist = [];
const customers = data[0].data;
customers.forEach(customer => {
/* Take any data you like for each customer here */
this.consolelist.push(customer.name);
});
});
And that will do it. You will have an array inside your component that is custom created for use by your template.
Here your this.consolelist
array will be simply ['Tom', 'Dick', 'Harry', 'Rumplestiltskin']
. You will still need to use something like ngFor
to display the customers in the template, but it should be much simpler since you've pulled out and formatted exactly the data from the API response that you need.
Upvotes: 1