23

我创建了一个角度应用程序,它从 json 文件中获取数据。但是我在用 html 显示数据时遇到了问题。很多变量都是荷兰语,我很抱歉。我对这一切也有点陌生:)

这是我的服务:

import {Injectable} from '@angular/core';
import {Http, RequestOptions, Response, Headers} from '@angular/http';
import {Observable} from "rxjs";
import {Afdelingen} from "./models";

@Injectable()
export class AfdelingService {
  private afdelingenUrl = '/assets/backend/afdelingen.json';
    constructor(private http: Http) {
      }

      getAfdelingen(): Observable<Afdelingen[]> {
        return this.http.get(this.afdelingenUrl)
          .map(this.extractData)
          .catch(this.handleError);
      }

      private extractData(res: Response) {
        let body = <Afdelingen[]>res.json();
        return body || {};
      }

      private handleError(error: any): Promise<any> {
        console.error('An error occurred', error);
        return Promise.reject(error.message || error);
      }

      addAfdeling(afdelingsNaam: string, afdeling: any): Observable<Afdelingen> {
        let body = JSON.stringify({"afdelingsNaam": afdelingsNaam, afdeling: afdeling});
        let headers = new Headers({'Content-Type': 'application/json'});
        let options = new RequestOptions({headers: headers});
        return this.http.post(this.afdelingenUrl, body, options)
          .map(res => <Afdelingen> res.json())
          .catch(this.handleError)
      }
    }

这是我的 json 文件的一部分:

{
  "afdelingen": [
    {
      "afdelingsNaam": "pediatrie",
      "kamernummer": 3.054,
      "patientid": 10001,
      "patientennaam": "Joske Vermeulen",
      "reden": "Appendicitis",
      "opname": "12/05/2017",
      "ontslag": "28/06/2017",
      "behandelingstype": "nazorg",
      "behandelingsomschrijving": "wondverzorging",
      "behandelingsdatum": "10/06/2017",
      "behandelingstijd": "10:20",
      "vegitarisch": false,
      "Opmerkingen": "",
      "sanitair": true,
      "kinderverzorgingsruimte": false,
      "salon": true,
      "hulp": true,
      "width": 5,
      "height": 5
    },
    {
      "afdelingsNaam": "pediatrie",
      "kamernummer": 3.055,
      "patientid": 10002,
      "patientennaam": "Agnes Vermeiren",
      "reden": "Beenbreuk",
      "opname": "18/05/2017",
      "ontslag": "30/06/2017",
      "behandelingstype": "nazorg",
      "behandelingsomschrijving": "wondverzorging",
      "behandelingsdatum": "10/06/2017",
      "behandelingstijd": "10:20",
      "vegitarisch": true,
      "Opmerkingen": "",
      "sanitair": true,
      "kinderverzorgingsruimte": false,
      "salon": true,
      "hulp": false,
      "width": 5,
      "height": 5
    }]}

组件:

import {Component, OnInit, Input} from '@angular/core';
import {Afdelingen} from "../models";
import {AfdelingService} from "../afdeling.service";
import {PatientService} from "../patient.service";


@Component({
  selector: 'app-afdeling',
  templateUrl: './afdeling.component.html',
  styleUrls: ['./afdeling.component.css']
})
export class AfdelingComponent implements OnInit {

 afdeling: Afdelingen[];
 errorMessage:string;

  constructor(private afdelingService: AfdelingService, private patientService: PatientService) { }

  ngOnInit() {
    this.getData()
  }

  getData() {
    this.afdelingService.getAfdelingen()
      .subscribe(
        data => {
          this.afdeling = data;
          console.log(this.afdeling);
        }, error => this.errorMessage = <any> error);

  }
}

和html:

<ul>
  <li *ngFor="let afd of afdeling">
    {{afd.patientid}}
  </li>
</ul>
4

4 回答 4

21

如错误消息所述,ngFor仅支持 Iterables 等Array,因此您不能将其用于Object.

改变

private extractData(res: Response) {
  let body = <Afdelingen[]>res.json();
  return body || {};       // here you are return an object
}

private extractData(res: Response) {
  let body = <Afdelingen[]>res.json().afdelingen;    // return array from json file
  return body || [];     // also return empty array if there is no data
}
于 2017-05-16T09:55:47.663 回答
17

请记住将 Observables 通过管道传递给异步,例如*ngFor item of items$ | async,您尝试到的*ngFor item of items$地方items$显然是一个 Observable,因为您使用$类似于 to 来标记它items$: Observable<IValuePair>,并且您的分配可能类似于this.items$ = this.someDataService.someMethod<IValuePair>()返回 T 类型的 Observable。

除此之外......我相信我已经使用了像这样的符号*ngFor item of (items$ | async)?.someProperty

于 2018-02-13T04:30:33.433 回答
5

您只需要async管道:

<li *ngFor="let afd of afdeling | async">
    {{afd.patientid}}
</li>

async在直接处理 Observables 时始终使用管道而不显式取消订阅。

于 2018-09-13T04:32:02.120 回答
2

我遇到了同样的问题,正如 Pengyy 建议的那样,这就是解决方法。非常感谢。

我在浏览器控制台上的问题:

浏览器控制台上的图像问题

PortafolioComponent.html:3 ERROR 错误:尝试区分“[object Object]”时出错。只允许使用数组和可迭代对象(…)

就我而言,我的代码修复是:

//productos.service.ts
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';

@Injectable()
export class ProductosService {

  productos:any[] = [];
  cargando:boolean = true;

  constructor( private http:Http) {
    this.cargar_productos();
  }

  public cargar_productos(){

    this.cargando = true;

    this.http.get('https://webpage-88888a1.firebaseio.com/productos.json')
      .subscribe( res => {
        console.log(res.json());
        this.cargando = false;
        this.productos = res.json().productos; // Before this.productos = res.json(); 
      });
  }

}
于 2018-01-01T15:41:18.863 回答