我有这样的服务..
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()
我的数据,那么我可以看到返回的响应。我猜这是因为我的天气变量在我访问时尚未定义,但我不确定正确的方法。
任何帮助,将不胜感激!
4 回答
只需使用
ngIf
来处理 undefine:使用安全操作员
我认为可能会返回响应,但返回的值不会分配给天气。所以{{。 6}}未定义它导致其属性未定义。尝试设置{{。的值。 7}}。
将
weather
声明为object
。