okayilltry
okayilltry

Reputation: 492

HTTP get service - cannot read property of undefined

I have a service like so..

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';

@Injectable()
export class WeatherProvider {
  loading: Boolean = true;
  private url: string = 'http://samples.openweathermap.org/data/2.5/weather?q=London,uk&appid=b1b15e88fa797225412429c1c50c122a1';

  constructor(public http: Http) {
  }

  getWeather(){
    return this.http.get(this.url).map(res => res.json());
  }
}

I'm using the service like this...

import { Component } from '@angular/core';
import { NavController, NavParams, ModalController, PopoverController } from 'ionic-angular';
import { WeatherProvider } from '../../providers/weather/weather';

@Component({
  providers: [WeatherProvider],
  selector: 'page-display-route',
  templateUrl: 'display-route.html',
})
export class DisplayRoutePage {

  weather: any;
  constructor(public weatherProvider: WeatherProvider ) {

              this.getWeather();
  }

  getWeather() {
    this.weatherProvider.getWeather().subscribe(d=>{
      this.weather = d;
    })
  }

And in my html I attempt to access the returned data like so...

<ion-content>
<h1>{{weather.cod}}</h1>
</ion-content>

But I receive the error

Cannot read property 'cod' of undefined

If I console.log() my data then I can see the returned response. I'm guessing this is because my weather variable is undefined at the point I'm accessing it but I'm unsure of the right way to go about this.

Any help would be appreciated!

Upvotes: 1

Views: 2035

Answers (4)

Swapnil Patwa
Swapnil Patwa

Reputation: 4099

Declare weather as object.

weather: any = {};

Upvotes: 0

Rahul Beniwal
Rahul Beniwal

Reputation: 677

I think response may be returned but returned value is not assigned to weather. So {{weather}} is not defined it results its property not defined. Try to set value of {{weather}}.

Upvotes: 0

Sajeetharan
Sajeetharan

Reputation: 222582

Use safe operator

<ion-content>
<h1>{{weather?.cod}}</h1>
</ion-content>

Upvotes: 2

Duannx
Duannx

Reputation: 8726

Just use ngIf to handle undefine:

<h1 *ngIf="weather">{{weather.cod}}</h1>

Upvotes: 1

Related Questions