我已成功从jsonplaceholder fake api https://jsonplaceholder.typicode.com/posts
获取数据我正在尝试使用angular 2 {{}}来绑定它,但我收到了以下错误。我不知道我做错了什么,如果有任何身体可以帮助我,那将是满满的。以下是我的代码和错误。
错误:无法找到'object'类型的不同支持对象'[object Object]'。 NgFor仅支持绑定到Iterables,例如Arrays。
import { Component } from '@angular/core';
import {BioService} from './bio.service'
import { Users } from './User';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'app works!';
values : any;
users: Users[];
errorMessage: string;
mode = 'Observable';
profile = {};
constructor(private bioservice:BioService)
{
}
ngOnInit(){
this.getHeroes();
debugger;
}
getHeroes() {
this.bioservice.getHeroes().subscribe(data => this.profile = data);
}
}
HTML模板:
<h1>
<div>
<ul *ngFor= "let user of profile">
<li>{{user.userId}}</li>
</ul>
</div>
</h1>
服务:
import { Injectable } from '@angular/core';
import { Http, Response, Headers, RequestOptions } from '@angular/http';
import {Observable} from 'rxjs/Rx';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import { Users } from './User';
@Injectable()
export class BioService {
private url = 'http://bioapideploy.azurewebsites.net/api/Users';
private placeholderurl = "https://jsonplaceholder.typicode.com/posts";
constructor(private http: Http) { }
getHeroes() {
debugger;
return this.http.get(this.placeholderurl)
.map((res:Response) => res.json());
}
private extractData(res: Response) {
debugger;
let body = res.json();
return body.data || { };
}
private handleError (error: Response | any) {
// In a real world app, you might use a remote logging infrastructure
debugger;
let errMsg: string;
if (error instanceof Response) {
const body = error.json() || '';
const err = body.error || JSON.stringify(body);
errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
} else {
errMsg = error.message ? error.message : error.toString();
}
console.error(errMsg);
return Observable.throw(errMsg);
}
}
答案 0 :(得分:1)
AppComponent
profile = {};
改为profile: any[];
答案 1 :(得分:0)
您似乎错过了async
声明中的*ngFor
管道。由于getHeroes()
返回Observable
,您需要使用此类async
管道让Angular知道提供给*ngFor
循环的数据是异步的。
<h1>
<div>
<ul *ngFor= "let user of profile | async">
<li>{{user.userId}}</li>
</ul>
</div>
</h1>