CHAMCHOUN
CHAMCHOUN

Reputation: 779

Error while accessing properties of object after GET request?

I am using a weather api in my angular app and this is an example response of the api.

I get my data via this function :

getTempByName(name) {
return this.http.get('https://api.weatherbit.io/v2.0/current?' + 'city=' + name + 
'&key=mykey');
}

and then assign it to an object via this code where weatherData is my Object :

weatherData: object;
this.fetch.getTempByName(this.name).subscribe(data => {
  if (data) {
    this.weatherData = data;
  } else {
    this.noty.notify('error', 'The city Name you entered is incorrect');
  }});
}

and then in my html I am using this code to show the data :

<div class="container" *ngIf="weatherData">
  <p class="country">{{weatherData.data[0].city_name}}</p>
  <p class="temp">{{weatherData.data[0].temp}}°</p>
</div>

Everything runs smoothly when I run the app on a local server but as soon as I build it via this command ng build --prod I have this error:

ERROR in src/app/weahter-info/weahter-info.component.html(8,22): Property 'data' does not exist on type 'object'. src/app/weahter-info/weahter-info.component.html(9,8): Property 'data' does not exist on type 'object'. src/app/weahter-info/weahter-info.component.html(10,31): Property 'data' does not exist on type 'object'. src/app/weahter-info/weahter-info.component.html(11,19): Property 'data' does not exist on type 'object'. src/app/weahter-info/weahter-info.component.html(14,73): Property 'data' does not exist on type 'object'. src/app/weahter-info/weahter-info.component.html(17,54): Property 'data' does not exist on type 'object'.

I tried to find a way to ignore the error via various methods but I couldn't, any help will be welcome.

Upvotes: 2

Views: 69

Answers (1)

Saurabh Yadav
Saurabh Yadav

Reputation: 3386

weatherData: object; change it to weatherData: any;

values come from API we want to opt-out of type checking and let the values pass through compile-time checks. To do so, we label these with the any type or you can create class or interface to avoid it

Upvotes: 4

Related Questions