我有这样的服务。
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()
我的数据,那么我可以看到返回的响应。我猜这是因为我的天气变量在我访问它时未定义,但我不确定正确的方法。
任何帮助将不胜感激!
使用安全运算符
<ion-content>
<h1>{{weather?.cod}}</h1>
</ion-content>
只需使用ngIf
来处理未定义的:
<h1 *ngIf="weather">{{weather.cod}}</h1>
我认为可能会返回响应,但返回的值没有分配给天气。所以 {{weather}} 没有定义,它的结果是它的属性没有定义。 尝试将值设置为 {{天气}}。
将weather
声明为object
。
weather: any = {};