vinayofficial
vinayofficial

Reputation: 482

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.

Upvotes: 1

Views: 2166

Answers (2)

Igor
Igor

Reputation: 62228

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.

Upvotes: 1

Stefan Svrkota
Stefan Svrkota

Reputation: 50633

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.

Upvotes: 2

Related Questions