0

I have a service which returns the following covid-19 data

{
    "data": {
        "total_cases": "14,664,059",
        "recovery_cases": "8,748,094",
        "death_cases": "609,279",
        "last_update": "Jul, 20 2020, 09:21, UTC",
        "currently_infected": "5,306,686",
        "cases_with_outcome": "9,357,373",
        "mild_condition_active_cases": "5,247,063",
        "critical_condition_active_cases": "59,623",
        "recovered_closed_cases": "8,748,094",
        "death_closed_cases": "609,279",
        "closed_cases_recovered_percentage": "93.0",
        "closed_cases_death_percentage": "7.0",
        "active_cases_mild_percentage": "99.0",
        "active_cases_critical_percentage": "1.0",
        "general_death_rate": "4.0"
    },
    "status": "success"
}

service file

@Injectable({
  providedIn: 'root'
})
export class CoviddataserviceService {

  private baseUrl='https://corona-virus-stats.herokuapp.com/api/v1/cases/general-stats';
  constructor(private http:HttpClient) { }

  getWorldData(): Observable<any>{
    return this.http.get(this.baseUrl);
  }
}

component.ts file

export class WorlddataComponent implements OnInit {

  public worlddataArray=[];

  constructor(private cdservice:CoviddataserviceService ) { }

  ngOnInit(): void {
  this.loadWorldData();
  }


  loadWorldData(){
   return this.cdservice.getWorldData().subscribe(data=>this.worlddataArray=data,error=>console.error(error));
     
  }
}

When I try to print that data in html as follows

<td>{{worlddataArray.total_cases}}</td>

it shows the following error

Property 'total_cases' does not exist on type 'any[]'.
<td>{{worlddataArray.total_cases}}</td>
                             ~~~~~~~~~~~

when I just type

 <td>{{worlddataArray}}</td>

It shows only

    [object Object]

I think the error is in my way of accessing that data in the html file.So please suggest a way to do it.Thank you.

1
  • try .subscribe(data=>this.worlddataArray=JSON.stringify(data), Commented Jul 20, 2020 at 11:24

1 Answer 1

1

use below code.

Declare worlddataArray as below:

  public worlddataArray:any = {};

Write your html code as below:

<td *ngIf="worlddataArray.data">{{worlddataArray.data.total_cases}}</td>
Sign up to request clarification or add additional context in comments.

2 Comments

It works. But can you specify why the *ngIf="worlddataArray.data" is used, without it data is shown on the web page but shows this on the console ''core.js:6241 ERROR TypeError: Cannot read property 'total_cases' of undefined''
Initially worlddataArray is empty, so i used *ngIf.

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.