无法使用 ngFor 显示数据

Unable to display data with ngFor

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

我的服务class

患者服务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 Error: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.

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

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

您的 extractdata 方法可能 returning 一个对象

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

将 return 值更改为数组

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