如何循环访问从 REST API 获得的响应对象并在 angular 中的视图中显示数据 2

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

我休息 api returns JSON 响应。如何绑定此数据以在 angular 2 中查看?

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

我想在视图中显示这些 ID。我尝试使用 ngFor directive.<div *ngFor="let lap of lapIDS">{{lap.lapID }}</div> 遍历它 我得到这个错误

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;

}

在组件中

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

在模板视图中

<p *ngFor="let item of array">
  {{ item.lapID }}
</p>

您的错误出在您的 extractData 函数中,您正在 returning body.data,但您的 JSON 不包含 data 对象,但是一个数组,将它更改为 body 应该可以工作,因为现在你正在 returning 一个空对象,显然不能迭代,所以将 return 更改为 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
  }