Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding how to call a REST Api and displaying the data from the response in Angular 2

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.

like image 575
Nikolay Hristov Avatar asked Sep 25 '22 08:09

Nikolay Hristov


1 Answers

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>
like image 78
Thierry Templier Avatar answered Sep 28 '22 06:09

Thierry Templier