HTTP 获取服务 - 无法读取未定义的 属性

HTTP get service - cannot read property of undefined

我有这样的服务..

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());
  }
}

我正在使用这样的服务...

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;
    })
  }

在我的 html 中,我尝试像这样访问返回的数据...

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

但是我收到错误

Cannot read property 'cod' of undefined

如果我 console.log() 我的数据,那么我可以看到返回的响应。我猜这是因为我的天气变量在我访问它时未定义,但我不确定正确的方法。

如有任何帮助,我们将不胜感激!

只需使用ngIf来处理undefine:

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

使用安全运算符

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

我认为可能会返回响应,但返回值未分配给天气。所以 {{weather}} 没有定义它导致它的 属性 没有定义。 尝试设置 {{weather}} 的值。

weather 声明为 object

weather: any = {};