请告诉我如何在角度2中调用http调用并使用ng-repeat显示数据?
这是我的代码 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']);
}
}
答案 0 :(得分:3)
首先,您需要将Http
实例注入到组件中:
export class AppComponent {
toDoModel;
constructor(private _router:Router,private http:Http) {
this.http.get('data.json')
.map(res => res.json())
}
}
有两种方法可以在ngFor
中显示您的数据:
订阅get
方法返回的observable
@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;
});
}
}
利用async
管道
@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());
}
}
在引导您的应用程序时,不要忘记指定HTTP_PROVIDERS
:
import {bootstrap} from 'angular2/platform/browser';
import {HTTP_PROVIDERS} from 'angular2/http';
import {AppComponent} from './app.component';
bootstrap(AppComponent, [ HTTP_PROVIDERS ]);
这是相应的plunkr:https://plnkr.co/edit/bdFeiiAqrPDtFUdguw7s?p=preview。
您还可以将HTTP处理放入专用服务中,如下所述:
答案 1 :(得分:0)
你需要它“注入”Http
才能使用它
constructor(private http: Http){
http.get('https://...')
.map(response => { response.json(); })
.subscribe(value => { this.data = value;})
}