简体   繁体   中英

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. Here is my working code:

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[]'

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)
        );
    }
}

This code is working in Plunkr but having error when I try it in my project. Please help to iterate the API values in my project. Thank you.

That's because you haven't assigned type to your getData variable. If you change getData = []; to getData: any = []; , your code should work. Other solution is to change compiler options in your tsconfig.json file:

"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.

The signature of your service method getConfiguration is

(): Observable<Response>

But the return type is not correct, it should be the type that the Observable will materialize. Example:

(): Observable<any[]>

You can make any a specific type.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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