I'm learning Angular 2 and I've been working with static arrays, and now I'm trying to learn more about reading remote data.
My app.component.ts
:
import {Component} from 'angular2/core';
import {Http, Response} from 'angular2/http';
import {Observable} from 'rxjs/Rx';
@Component({
selector: 'my-app',
template:`
<h1>Angular2 HTTP Demo App</h1>
<h2>Foods</h2>
<ul>
<li *ngFor="#doc of docs">{{doc.id}}</li>
</ul>
`
})
export class AppComponent {
public foods;
public books;
public movies;
constructor(private http: Http) { }
ngOnInit() {
this.getFoods();
}
getFoods() {
this.http.get('http://my API URL')
.map((res:Response) => res.json())
.subscribe(
data => { this.foods = data},
err => console.error(err),
() => console.log('done')
);
}
}
This is how my API url show the results:
My goal is to loop each array item and show the data inside it (id, placeID, etc..)
This is my app, which makes no iteration at all:
How I can loop with the *ngFor
each of ths json array items?
Plunker
To loop over Array:
<li *ngFor="let doc of docs">{{doc.id}}</li>
To loop over Object Properties:
You will have to generate an Array
of the object properties
generateArray(obj){
return Object.keys(obj).map((key)=>{ return obj[key]});
}
and use it like
<li *ngFor="let doc of docs">
<span *ngFor="let v of generateArray(doc)"> {{v}} </span>
</li>
Or you can use as Pipe.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With