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

I am new to Angular 2 and Typescript, so please excuse me for this question, but I cannot figure out how to use the data after a successful Api REST call. I made a plunker for my example, so it will be easier for me to explain what I'm doing.

Please ignore unused imports when viewing the example.

The function call is getWeatherworking 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 data? I mean, should I make the object look like a json response and use it if for displaying data and how?

Edit: Here is a working example with my code.

+4
2

, .

HTTP , , .

( ).

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;
       });
}

ngFor, {{...}} . , , , , ngIf Elvis (?).

<div>{{weather?.someProperty}}</div>
+3

, json any . . :

countryData: any;

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.countryData = res)
        );
}

, :

countryData: Country;

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.countryData = <Country>res)
        );
}

, , Country , , .

+1

Source: https://habr.com/ru/post/1629051/


All Articles