I'm new in Angular 2 and Typescript so please excuse me for this question but I can't understand how to consume the data after successfully calling a REST Api. I made a plunker for my example so it will be easier to explain what I'm tring to do.
Please ignore unused imports when viewing the example.
Calling the function getWeather
works fine.
getWeather(query) {
const endpoint = 'http://api.openweathermap.org/data/2.5/weather?q=London,uk&appid=44db6a862fba0b067b1930da0d769e98';
return this.http
.get(endpoint)//, {search: searchParams})
.map(res => res.json().main)
.subscribe(res => console.log('weather json response = ' + JSON.stringify(res))
);
}
But how to store the data? I mean do I have to make an object similar like the json response and use if for displaying the data and how?
Edit: Here is a working example with my code.
When reverting the data, you simply need to set them as property of the component using the this keyword.
In the case of HTTP request, the data are there when the first callback registered using the subscribe method is called.
Using an arrow function to define this callback allows to use the component instance through the this keyword (contextual this in this case).
getWeather(query) {
const endpoint = 'http://api.openweathermap.org/data/2.5/weather?q=London,uk&appid=44db6a862fba0b067b1930da0d769e98';
return this.http
.get(endpoint)//, {search: searchParams})
.map(res => res.json().main)
.subscribe(res => {
this.weather = data;
});
}
Then the template can reference such properties to display data with ngFor, {{…}} or interpolation. Be careful to handle the asynchronous aspect of observable with for example the async pipe, ngIf or the Elvis operator (?).
<div>{{weather?.someProperty}}</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With