如何循环遍历从REST API获取的响应对象并在角度2的视图中显示数据

时间:2017-03-22 14:43:08

标签: javascript json angular angular-http ngfor

我有休息api,它返回JSON响应。如何绑定此数据以角度2查看?

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

我想在视图中显示这些ID。我尝试使用ngFor directive.<div *ngFor="let lap of lapIDS">{{lap.lapID }}</div>循环播放它我收到此错误

  

无法找到'object'类型的不同支持对象'[object Object]'。 NgFor仅支持绑定到Iterables,例如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;

}

2 个答案:

答案 0 :(得分:0)

组件中的

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

在模板视图中

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

答案 1 :(得分:0)

您的错误在extractData函数中,您正在返回body.data,但您的JSON不包含data对象,而是一个数组,将其更改为{{1}应该工作,因为现在你正在返回一个空对象,显然无法迭代,所以将返回值改为body

body