First you need to inject an Http
instance into you component:
export class AppComponent {
toDoModel;
constructor(private _router:Router,private http:Http) {
this.http.get('data.json')
.map(res => res.json())
}
}
There are then two ways to display your data in an ngFor
:
By subscribing on the observable returned by the get
method
@Component({
template: `
<ul>
<li *ngFor="#elt of elements">{{elt.name}}</li>
</ul>
`
})
export class AppComponent {
toDoModel;
constructor(private _router:Router,private http:Http) {
this.http.get('data.json')
.map(res => res.json())
.subscribe(data => {
this.elements = data;
});
}
}
By leveraging the async
pipe
@Component({
template: `
<ul>
<li *ngFor="#elt of elements | async">{{elt.name}}</li>
</ul>
`
})
export class AppComponent {
toDoModel;
constructor(private _router:Router,private http:Http) {
this.elements = this.http.get('data.json')
.map(res => res.json());
}
}
Don't forget to specify HTTP_PROVIDERS
when bootstrapping your application:
import {bootstrap} from 'angular2/platform/browser';
import {HTTP_PROVIDERS} from 'angular2/http';
import {AppComponent} from './app.component';
bootstrap(AppComponent, [ HTTP_PROVIDERS ]);
Here is the corresponding plunkr: https://plnkr.co/edit/bdFeiiAqrPDtFUdguw7s?p=preview.
You could also put your HTTP processing into a dedicated service as described below: