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

5

我刚开始学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响应的对象来显示数据,如果需要,要如何使用? 编辑:这里有一个带有我的代码的可运行示例。
2个回答

3

当恢复数据时,您只需要使用 this 关键字将它们设置为组件的属性即可。

对于 HTTP 请求,当使用 subscribe 方法注册第一个回调函数时,数据就已经存在了。

使用箭头函数来定义这个回调函数可以通过 this 关键字(在这种情况下是上下文的 this)使用组件实例。

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、{{...}}或插值来显示数据。注意处理observable的异步方面,例如使用async管道、ngIf或Elvis运算符(?)。

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

{{weather?.someProperty}} 是我要找的内容。 我不知道为什么,但当我使用{{weather.someProperty}}(没有Elvis运算符)时,它不起作用。 我会在我的第一条评论中更新可行的示例。谢谢。 - Nikolay Hristov
1
不客气!在Angular2中,您不能在表达式中使用未定义对象上的属性。在异步处理中,对象在开始时是未定义的... - Thierry Templier

1
您可以创建一个模型类来模拟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 或您命名的任何类,则该类不会具有您在该类上定义的任何可用方法。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接