user1731770 user1731770 -4 years ago 102
JSON Question

How to loop through response object obtained from REST API and display data in the view in angular 2

I have rest api which returns JSON response. How to bind this data to view in angular 2?

[{"lapID":"3445656"},{"lapID":"374657"},{"lapID":"375555"},{"lapID":"3445657"},{"lapID":"3445659"}]


I want to display these IDs in the view. I tried to loop through it using
ngFor directive.<div *ngFor="let lap of lapIDS">{{lap.lapID }}</div>
I get this error


Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.


component.ts
import {OnInit, Component} from '@angular/core';
import {TemperatureService} from './temperature.service'; // import service
import {Temperature} from './temperature'; // import your model

@Component({

providers: [TemperatureService],
template: `
<ul>
<li *ngFor="let device of devices">{{device.lapID}}</li>
</ul>

`
})

export class TemperatureComponent implements OnInit{

devices;
errorMessage: string;

constructor(private temperatureService: TemperatureService){}

ngOnInit(){

this.getDevices();

}

getDevices(){

this.temperatureService.getDeviceIDS()

.subscribe(

devices =>

this.devices = devices,

error => this.errorMessage = <any>error // Store error message receiver from server

);

}

}

Service.ts
import {Http, Response} from '@angular/http';

import {Injectable} from '@angular/core';

import {Observable} from 'rxjs/Observable';

import 'rxjs/add/operator/map';

import 'rxjs/add/operator/catch';



import {Temperature} from './temperature';



@Injectable()

export class TemperatureService{

private deviceIDUrl = '/api/temperatures/'; // URL to web API

constructor(private http: Http) { }

// GET request To access data and specify observable type from model

getDeviceIDS(): Observable<Temperature[]>{

return this.http.get(this.deviceIDUrl)

.map(this.extractData) // to check for the status code

.catch(this.handleError); // to check error

}



// Extracts from response

private extractData(res: Response) {

if (res.status < 200 || res.status >= 300) {

throw new Error('Bad response status: ' + res.status);

}

let body = res.json();

return body.data || { };

}



// To handle Error

private handleError (error: Response | any) {

// In a real world app, we might use a remote logging infrastructure

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

}

}
model.ts
export class Temperature{

deviceId: string;

}

Answer Source

Your error is in your extractData function, you are returning body.data, but your JSON doesn't contain a data object, but an array, changing it to just body should work, because now you are currently returning an empty object, which obviously cannot be iterated, so change the return to just body:

 private extractData(res: Response) {
     if (res.status < 200 || res.status >= 300) {
       throw new Error('Bad response status: ' + res.status);
     }
    let body = res.json(); 
    return body || { }; // here
  }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download