Undefined response request while using get HttpClient api call in angular 10

34 Views Asked by At

On doing console.log of Api response I get undefined as output. Since I am new to angular your feedback and suggestions would be of great help.

Here is the raw response that I get from the api get call from the url-

{"page":1,"per_page":10,"total":1,"total_pages":1,"data":[{"name":"Dallas","weather":"12 degree","status":["Wind: 2Kmph","Humidity: 5%"]}]}

Here is the component where I am doing Http client get call

@Component({
 selector: 'weather-finder',
 templateUrl: './weatherFinder.component.html',
 styleUrls: ['./weatherFinder.component.scss']
 })
export class WeatherFinder implements OnInit {
 constructor( private http: HttpClient)
 {
 }
  search: string;

 name:any=null;
 weather:any;
 wind:any;
 humidity:any;
 abc:string;

 fetch(value)
 {

  var url= "https://jsonmock.hackerrank.com/api/weather?name="+this.search;
  return(this.http.get<any>(url));
  }

 onFetch(abc:string)
 {
  this.search=abc;
  this.fetch(this.search).subscribe((response:any)=>{
  console.log(response);
  this.name=response.data.name;
  this.weather=response.data.weather;
 // this.wind=response.data.status.wind;
 // this.humidity=response.status.Humidity;
 console.log(response.data.weather);     // gives undefined
})
}
1

There are 1 best solutions below

1
Naren Murali On

Data is an array so you must specify which index you want to access the weather on!

Before

 // this.wind=response.data.status.wind;    // gives undefined
 // this.humidity=response.status.Humidity;    // gives undefined
console.log(response.data.weather);     // gives undefined

After

this.wind=response.data[0].status[0];    // will work!
this.humidity=response.data[0].status[1];    // will work!
console.log(response.data[0].weather);     // will work!