【问题标题】:Unable to display data with ngFor无法使用 ngFor 显示数据
【发布时间】:2018-02-17 02:17:49
【问题描述】:

我正在尝试使用 angular 的 get 方法从包含 json 数据的 url 中获取患者的详细信息。

我的服务类

Patient Service class.ts

@Injectable()
export class PatientService{
    url="http://localhost:8080/rest/patientC";

    constructor(private http:Http){}

    getPatientWithObservale():Observable<patient[]>{
        return this.http.get(this.url)
                        .map(this.extractdata)
                        .catch(this.handleErrorObservable);
    }
private extractdata(res:Response){
        let body=res.json();
        console.log(body.data);
        return body.data || {};
    }
}

**Observable Component class.ts**

export class ObservableComponent implements OnInit{
    patients:patient[];
    errorMessage: string;
    patientName: string;
    patient=new patient();

    constructor(private patientService: PatientService){}
    ngOnInit(){
        this.fetchPatient();
    }

    fetchPatient():void{
        this.patientService.getPatientWithObservale()
                            .subscribe(patients=>this.patients = patients,
                            error=>this.errorMessage=error);

    }
}

**Observable component.html**

<h3>Patient Details with Observable </h3>
<table>
    <tr>
        <th>Id</th>
        <th>First Name</th>
        <th>Last Name</th>
        <th>Age</th>
        <th>Gender</th>
        <th>Address</th>
        <th>Disease</th>
        <th>Contact No</th>
    </tr>
    <tr *ngFor="let paty of patients">
        <td>{{paty.id}}</td>
        <td>{{paty.firstname}}</td>
        <td>{{paty.lastname}}</td>
        <td>{{paty.gender}}</td>
        <td>{{paty.age}}</td>
        <td>{{paty.address}}</td>
        <td>{{paty.contactNo}}</td>
        <td>{{paty.disease}}</td>
    </tr>
</table>

错误:

ObservableComponent.html:13 ERROR 错误:找不到“object”类型的不同支持对象“[object Object]”。 NgFor 只支持绑定到 Arrays 等 Iterables。

似乎 ngFor 无法绑定值。我该如何解决这个问题?

【问题讨论】:

  • 只是“患者”没有 ngfor 期望的数组格式。检查http响应格式

标签: json angular angular2-template angular2-ngfor


【解决方案1】:

由于错误状态,ngFor 指令仅适用于可迭代对象。

您的 extractdata 方法可能会返回一个对象

private extractdata(res:Response){
        let body=res.json();
        console.log(body.data);
        return body.data || {}; <--- returning object
    }
}

将返回值改为数组

private extractdata(res:Response){
        let body=res.json();
        console.log(body.data);
        return body.data || []; <-- change
    }
}

【讨论】:

  • 我试过但没用,但我找到了解决方案。而不是返回 'body.data || {}; ' 我把它改成 'body || {}'。我不知道为什么前者不起作用,但后者起作用。谁能解释一下?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-09-18
  • 2017-01-06
  • 2019-09-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多