Xenohs Xenohs - 2 months ago 8
TypeScript Question

How do I display a single JSON object in the template

I have a detail component that is supposed to display the 5 day forecast for a given city and I am able to retrieve the data successfully when I call the http.get(Url) method.

However I'm not sure how to bind this JSON data to my view.

*I know how to display data in a list view but I'm not sure how to display a single object.

Detail Component:

@Component({
selector: 'app-weather-detail',
templateUrl: './weather-detail.component.html',
styleUrls: ['./weather-detail.component.css']
})
export class WeatherDetailComponent implements OnInit {

public weatherDetailItem: any;
private name: any;

constructor(
private weatherService: WeatherService,
private route: ActivatedRoute,
private location: Location
){}

//This method will retrieve the 5 day forecast for the city name in the route param
getWeatherItem(){
this.weatherService.fetchDetail(this.name)
.do(data => console.log(data))
.subscribe((data) => {
this.weatherDetailItem = data;
})
}

goBack(): void {
this.location.back();
}

ngOnInit() {
this.name = this.route.snapshot.params['name'];
this.getWeatherItem();
}


}


fetchDetail() calls the http.get method and grabs me this data:

http://api.openweathermap.org/data/2.5/forecast?q=Dallas&units=imperial&appid=f630449a4407b742703bf37d8e8c9057

In my template I have this:

<div>
<h3>CITY:</h3>
<h3>{{weatherDetailItem}}</h3>
</div>


When I actually load the page, it gives me City: [object Object]. I tried to access that JSON data with {{weatherDetailItem.city.name}} but received an error. Any ideas?

Thanks

Answer

You can use ?. operator (for async call). So, It should be

{{weatherDetailItem?.city.name}}

Comments