How to bind data only if it exists?

I am sure it is an easy question.

I am binding
{{data.weatherforecast.city}}.

However, until the http request finished, the data doesn’t exist=> so I have na error. How should I handle that?

Thanks.

EXCEPTION: Error in ./HomePage class HomePage - inline template:14:13 caused by: Cannot read property 'city' of undefined

As far as I know, you can cannot directly bind the response data directly to the view.Use it as below,

export class WeatherForecast {
weatherforecast ={};
constructor(){
this.weatherforecast = data.weatherforecast; //response from server
}
}

In View,bind it as {{weatherforecast.city}}

1 Like

Hum. it doesn’t work:

    export class WeatherForecast {
 public   weatherforecast:any;
    constructor(){
    this.weatherforecast = this.http.get('http://api.wunderground.com/api/Mykey/geolookup/conditions/q/mycity.json').map(res => res.json()).subscribe(data => {
            console.log(data);
           return data;
        });
    }

Should I instantiate an dummy object in the constructor with all the property?

I think instantiating a dummy object is the best idea, however you can use the Elvis operator in this situation as well. The biggest problem is here:

this.weatherforecast = this.http.get('http://api.wunderground.com/api/Mykey/geolookup/conditions/q/mycity.json').map(res => res.json()).subscribe(data => {
            console.log(data);
           return data;
        });
    }

Instead, you want this:

this.http.get('http://api.wunderground.com/api/Mykey/geolookup/conditions/q/mycity.json').map(res => res.json()).subscribe(data => {
          this.weatherforecast = data;
        });
    }

This is also a reason you should try to avoid the crutch of any as much as possible. If weatherforecast was properly typed, TypeScript could warn you at compile time that you are assigning it a subscription, which would make no sense.

Ok. Thanks. It gonna go this way.