Reputation: 12729
could you please tell how to call http call in angular 2 and display data using ng-repeat ?
here is my code http://plnkr.co/edit/u6LXrvGuC6f3bOT1tsaZ?p=preview
import {Component,View} from 'angular2/core';
import {Http, HTTP_PROVIDERS} from 'angular2/http';
import {Router} from 'angular2/router';
@Component({
templateUrl: 'home/home.html'
})
export class AppComponent {
toDoModel;
constructor(private _router:Router) {
http.get('data.json')
.map(res => res.json())
}
onclck(inputValue){
alert(inputValue)
this._router.navigate(['Second']);
}
}
Upvotes: 0
Views: 1415
Reputation: 657308
You need it "inject" Http
in order to use it
constructor(private http: Http){
http.get('https://...')
.map(response => { response.json(); })
.subscribe(value => { this.data = value;})
}
Upvotes: 0
Reputation: 202176
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:
Upvotes: 3