我一直试图通过angular2从api(http://www.cricapi.com/how-to-use.aspx)获得响应。我不知道我做错了什么?这是我的代码 -
//matchlist.component.ts
@Component({
selector: 'match-list',
template: `
<ul>
<li *ngFor="let m of matches">
<p>{{m.title}}</p>
</li>
</ul>
`,
providers: [MatchListService]
})
export class MatchList implements OnInit{
matches: Match[] = [];
object: any;
constructor(private matchservice: MatchListService){
}
ngOnInit(){
this.matchservice.getMatchList()
.subscribe(
matches => this.matches = matches,
err => {}
);
}
}
这是我的服务类 -
@Injectable()
export class MatchListService{
private matchListUrl = 'http://cricapi.com/api/cricket/';
constructor (private http: Http) {
}
getMatchList(): Observable<Match[]>{
return this.http.get(this.matchListUrl, [{}])
.map((res:any) => res.json()
.catch(this.handleError));
}
请告诉我,如果我做错了吗?这是我与api的第一个前任!
答案 0 :(得分:1)
我不确定您要编写的语言是什么,但是使用常规角度,您只需将JSON返回的结果分配给变量,它将保存完整的JSON对象,如下所示:
$scope.data = [];
$http({url: url}).then(function (rs) {
console.log(rs);
$scope.data = rs.data;
});