[英]How to iterate API data using ngFor in Angular 2
我是Angular 2的新手,我想以表格形式显示所有API数据。 这是我的工作代码:
http://plnkr.co/edit/CB3oGppm4fvoEExfDSRc?p=preview
但是,当我在文件中使用此代码时,出现错误:
类型“ Response”不能分配给类型“ any []”
test.component.html:
<h1>{{getData[0]?.name}}</h1>
<h1>{{getData[0]?.time}}</h1>
<div *ngFor="let item of getData">
<span>{{item?.name}}</span>
</div>
app.component.ts
import { Component } from '@angular/core';
import { ConfigurationService } from './ConfigurationService';
@Component({
selector: 'app-root',
templateUrl: './app.component.html'
})
export class AppComponent {
getData = [];
constructor(private _ConfigurationService: ConfigurationService)
{
console.log("Reading _ConfigurationService ");
//console.log(_ConfigurationService.getConfiguration());
this._ConfigurationService.getConfiguration()
.subscribe(
(data)=> {
this.getData = data;
console.log(this.getData);
},
(error) => console.log("error : " + error)
);
}
}
这段代码在Plunkr中运行,但是在我的项目中尝试时出现错误。 请帮助迭代我项目中的API值。 谢谢。
这是因为您尚未将类型分配给getData
变量。 如果更改getData = [];
to getData: any = [];
,您的代码应该可以正常工作。 其他解决方案是更改tsconfig.json
文件中的编译器选项:
"compilerOptions": {
"noImplicitAny": false
}
如果将noImplicitAny
设置为false
,则不必为变量分配类型,如果不隐式设置变量的类型,则它将自动设置为any
类型。
服务方法getConfiguration
的签名是
(): Observable<Response>
但是返回类型不正确,它应该是Observable将实现的类型。 例:
(): Observable<any[]>
您可以指定any
特定类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.