简体   繁体   English

如何在Angular 2中使用ngFor迭代API数据

[英]How to iterate API data using ngFor in Angular 2

I am new in Angular 2 and I want to display all the API data in tabular form. 我是Angular 2的新手,我想以表格形式显示所有API数据。 Here is my working code: 这是我的工作代码:

http://plnkr.co/edit/CB3oGppm4fvoEExfDSRc?p=preview http://plnkr.co/edit/CB3oGppm4fvoEExfDSRc?p=preview

But when I am using this code in my files, I am having an error: 但是,当我在文件中使用此代码时,出现错误:

Type 'Response' is not assignable to type 'any[]' 类型“ Response”不能分配给类型“ any []”

test.component.html: 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 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)
        );
    }
}

This code is working in Plunkr but having error when I try it in my project. 这段代码在Plunkr中运行,但是在我的项目中尝试时出现错误。 Please help to iterate the API values in my project. 请帮助迭代我项目中的API值。 Thank you. 谢谢。

That's because you haven't assigned type to your getData variable. 这是因为您尚未将类型分配给getData变量。 If you change getData = []; 如果更改getData = []; to getData: any = []; to getData: any = []; , your code should work. ,您的代码应该可以正常工作。 Other solution is to change compiler options in your tsconfig.json file: 其他解决方案是更改tsconfig.json文件中的编译器选项:

"compilerOptions": {
    "noImplicitAny": false
}

If you set noImplicitAny to false , you don't have to assign type to variables, if you don't implicitly set variable's type, it will be set to any automatically. 如果将noImplicitAny设置为false ,则不必为变量分配类型,如果不隐式设置变量的类型,则它将自动设置为any类型。

The signature of your service method getConfiguration is 服务方法getConfiguration的签名是

(): Observable<Response>

But the return type is not correct, it should be the type that the Observable will materialize. 但是返回类型不正确,它应该是Observable将实现的类型。 Example: 例:

(): Observable<any[]>

You can make any a specific type. 您可以指定any特定类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM