Nik*_*tov 5 typescript angular
我是Angular 2和Typescript的新手,所以请为这个问题对不起,但在成功调用REST Api之后,我不明白如何使用数据。我为示例制作了一个小插曲,因此可以更轻松地说明我要执行的操作。
查看示例时,请忽略未使用的导入。
调用该函数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))
);
}
Run Code Online (Sandbox Code Playgroud)
但是如何存储数据?我的意思是我必须使一个类似于json响应的对象,并使用if来显示数据以及如何显示吗?
编辑: 这是我的代码的工作示例。
恢复数据时,您只需使用 this 关键字将它们设置为组件的属性即可。
\n\n对于 HTTP 请求,当调用使用 subscribe 方法注册的第一个回调时,数据就在那里。
\n\n使用箭头函数定义此回调允许通过 this 关键字(在本例中为上下文 this)使用组件实例。
\n\ngetWeather(query) {\n const endpoint = 'http://api.openweathermap.org/data/2.5/weather?q=London,uk&appid=44db6a862fba0b067b1930da0d769e98';\n return this.http\n .get(endpoint)//, {search: searchParams})\n .map(res => res.json().main)\n .subscribe(res => {\n this.weather = data;\n });\n}\nRun Code Online (Sandbox Code Playgroud)\n\n然后模板可以引用这些属性来使用 ngFor、{{\xe2\x80\xa6}} 或插值来显示数据。请小心处理 observable 的异步方面,例如使用异步管道、ngIf 或 Elvis 运算符 (?)。
\n\n<div>{{weather?.someProperty}}</div>\nRun Code Online (Sandbox Code Playgroud)\n
| 归档时间: |
|
| 查看次数: |
21790 次 |
| 最近记录: |