1

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!

okayilltry
  • 482
  • 1
  • 5
  • 18
  • 1
    Possible duplicate of [Observable type error: cannot read property of undefined](https://stackoverflow.com/questions/34734671/observable-type-error-cannot-read-property-of-undefined) – AT82 Jul 21 '17 at 15:56
  • Please make an attempt to even find an answer before posting. Just googling that error gives you plenty of Q&A... – AT82 Jul 21 '17 at 15:57
  • I did attempt to find an answer but couldn't find an ionic specific answer so I thought there may be some better practice when using ionic – okayilltry Jul 21 '17 at 17:25

4 Answers4

2

Use safe operator

<ion-content>
<h1>{{weather?.cod}}</h1>
</ion-content>
Sajeetharan
  • 216,225
  • 63
  • 350
  • 396
1

Just use ngIf to handle undefine:

<h1 *ngIf="weather">{{weather.cod}}</h1>
Duannx
  • 7,501
  • 1
  • 26
  • 59
0

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}}.

Rahul Beniwal
  • 639
  • 4
  • 9
0

Declare weather as object.

weather: any = {};
Swapnil Patwa
  • 4,069
  • 3
  • 25
  • 37