【发布时间】:2020-08-14 04:36:20
【问题描述】:
我正在学习 js fetch。 我正在尝试从响应中获取 temp 的值并在我的 component.js 中显示该值
weather.component.js
```
myApp.component('weatherComponent', {
template:"<p>Weather: {{vm.weather}}</p>",
controllerAs: 'vm',
controller: function WeatherController($scope,$element, $attrs) {
vm = this;
var apikey = "";
var city = "London";
fetch("https://api.openweathermap.org/data/2.5/weather?q="+city+"&appid=" + apikey)
.then(function(response) {
vm.weather = response.main.temp;
console.log("weather: "+ vm.weather);
return response.json();
})
.then(function(myJson) {
console.log(myJson);
});
}
});
```
index.html
```
<weather-component></weather-component>
<script src="utils.js"></script>
<script src="weather.component.js"></script>
```
In utils it is initialized var myApp = angular.module('myApp', []);
API 响应地址:https://openweathermap.org/current
【问题讨论】:
-
我的 AngularJs 时代已经远远落后了,但在我看来,您需要使用箭头函数才能访问 then.js 内部的外部范围。所以 .then((response) => { vm.weather = response.result // 或其他东西,而不是使用 function 关键字
标签: angularjs rest fetch-api openweathermap