2017-09-08 143 views
2

我想從包含json數據的url中使用get方法獲取患者詳細信息。無法使用ngFor顯示數據

我的服務類

病人服務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無法綁定值。我該如何解決這個問題?

+0

這只是「病人」不具有陣列格式預期ngfor。檢查http響應格式 – Vega

回答

0

由於錯誤狀態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 
    } 
} 
+0

我試過但它沒有工作,但我得到了解決方案。而不是返回'body.data || {}; '我改變了'身體|| {}」。我不知道爲什麼前者沒有工作,但後者做到了。 任何人都可以解釋它嗎? –