Trying to display two Arrays from API

Viewed 56

I have started learning typescript/ionic and I'm trying to display 2 different arrays from an API. My typescript code will only display the first array this.WeatherData = data.weather;. I also trying to display this.WeatherData = data.main;. I have included the API array code as well. Any help is appreciated thanks.

API Code

{
   "coord":{
      "lon":-9.05,
      "lat":53.27
   },
   "weather":[
      {
         "id":801,
         "main":"Clouds",
         "description":"few clouds",
         "icon":"02d"
      }
   ],
   "base":"stations",
   "main":{
      "temp":287.16,
      "feels_like":281.91,
      "temp_min":284.26,
      "temp_max":289.15,
      "pressure":1023,
      "humidity":44
   },
   "visibility":10000,
   "wind":{
      "speed":5.1,
      "deg":250
   },
   "clouds":{
      "all":20
   },
   "dt":1586623534,
   "sys":{
      "type":1,
      "id":1569,
      "country":"IE",
      "sunrise":1586583899,
      "sunset":1586633331
   },
   "timezone":3600,
   "id":2964180,
   "name":"Galway",
   "cod":200
}

HTML page

<ion-header>
  <ion-toolbar>
    <ion-buttons slot="start">
      <ion-back-button></ion-back-button>
    </ion-buttons>
    <ion-title>Weather for Galway</ion-title>
  </ion-toolbar>
</ion-header>

<ion-content>
  <ul>
    <li *ngFor="let data of WeatherData">
      <h3>Outside it is/has: {{data.description}}</h3>
      <h3>Current tempature is: {{data.temp}}</h3>
    </li>
  </ul>
</ion-content>

Typescript code

import { Component, OnInit } from '@angular/core';
import {WeatherService} from '../Services/weather.service';
@Component({
  selector: 'app-weather',
  templateUrl: './weather.page.html',
  styleUrls: ['./weather.page.scss'],
})
export class WeatherPage implements OnInit {
WeatherData:any=[];
  constructor(private weatherService:WeatherService) { }

  ngOnInit() {
    this.weatherService.getWeatherData().subscribe(
      (data)=>{
        this.WeatherData = data.weather;
        this.WeatherData = data.main;

      }
    );
  }

}
1 Answers

main is not an array but object.

If you want to loop through an object you need to use keyvalue pipe.

Transforms Object or Map into an array of key value pairs.

@Component({
  template: `<div *ngFor="let item of data | keyvalue">
      {{item.key}} - {{item.value}}
    </div>`
})
export class MyComponent {
  data = { "key": "value", "key2": "value2" };
}
Related