2

1- Image link for result of JSON data

I have JSON data in an array and I can display an individual part of the array in my HTML code. However, i am unable to display things like display all of names in the full array (for eg I can only access array[0])

ts file

patients: any[] = [];

this.viewService.viewPatient().subscribe(res => {
      this.patients = [res];
      console.log('data');
      console.log(res);
    });

html file

 // This works
 <ion-item *ngFor="let patient of patients">
       Name: {{patient.patients.data[0].FirstName}}
 </ion-item>

 // Doesnt work
 <ion-item *ngFor="let patient of patients"> (1) 
        Name: {{patient.patients.data.FirstName}}
 </ion-item>

viewpatient()

viewPatient() {
    return this.http.get(apiUrl + 'viewPatient.php');
  }
2
  • Please show the response console.log(this.patients) Commented Jun 18, 2019 at 10:12
  • 1
    Link for image i.sstatic.net/ZSuU5.png Commented Jun 18, 2019 at 10:18

2 Answers 2

2

In viewPatient() api assign res.patients.data directly to this.patients

this.viewService.viewPatient().subscribe(res => {
      this.patients = res.patients.data;
      console.log('data');
      console.log(res);
    });

then on template use as below

<ion-item *ngFor="let patient of patients">
       Name: {{patient.FirstName}}
 </ion-item>
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks very much it works! Any idea why in VSC it displays --- Property 'patients' does not exist on type 'Object'.
Can you show the viewPatient() method call ?, might you are returning type as Object or any instead of specific response type. also for patients array you can create user-defined type using interface.
👍 totally agree with @Ankit solution but as another option we can use async pipe
1

Try like this:

<ion-item *ngFor="let patient of patients?.patients?.data">
       Name: {{patient.FirstName}}
</ion-item>

or you can assign data array directly in patients

TS:

patients: any[] = [];

this.viewService.viewPatient().subscribe(res => {
     this.patients = res.patients.data;
});

Template:

<ion-item *ngFor="let patient of patients">
       Name: {{patient.FirstName}}
</ion-item>

3 Comments

Getting an error of 'Cannot read property 'data' of undefined'
Edited, add ? You got that error as it took some time to load the patients data
@c-mac, I have added this answer before this edited, is there any specific reason for marking this as right, and not that, because as you told my solution is worked for you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.