繁体   English   中英

了解如何调用REST Api并在Angular 2中显示响应中的数据

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

我是Angular 2和Typescript的新手,所以请原谅我这个问题,但是在成功调用REST Api之后我无法理解如何使用数据。 我为我的例子做了一个plunker ,所以更容易解释我要做的事情。

查看示例时请忽略未使用的导入。

调用函数getWeather工作正常。

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

但是如何存储数据呢? 我的意思是我必须创建一个类似json响应的对象,并使用if如何显示数据以及如何?

编辑: 是我的代码的一个工作示例。

还原数据时,只需使用this关键字将它们设置为组件的属性即可。

在HTTP请求的情况下,当调用使用subscribe方法注册的第一个回调时,数据就在那里。

使用箭头函数定义此回调允许通过this关键字使用组件实例(在本例中为contextual)。

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>

您确实可以创建一个类来模拟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或您为其命名的任何名称,那么它将不具有您在该类上定义的任何可用方法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM