【问题标题】:Hi I am learning about angularjs. I want to get the TEMP from one json and display that value in my component. I dont konw what I am doing wrong嗨,我正在学习 angularjs。我想从一个 json 中获取 TEMP 并在我的组件中显示该值。我不知道我做错了什么
【发布时间】: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


【解决方案1】:
  1. 从 json 中获取元素:

controller.weather = response.weather[0].description;

  1. 解决方法: 创建一个服务,这样我就可以获取数据并更改组件。 我放弃了使用“fetch”的想法。

weather.service.js

```myApp.service('weatherService', function($http, $q) {
    this.getWeather = function (apikey, city) {
        var deferred = $q.defer();
        // HTTP call
        $http.get("https://api.openweathermap.org/data/2.5/weather?q="+city+"&appid=" + apikey)
            .then(function(response) {
                deferred.resolve(response.data);
            }, function(response){
                deferred.reject(response);
            });
        return deferred.promise;
    };
});
 ```

weather.component.js

``` 
 myApp.component('weatherComponent', {
  template:"<p>Weather: {{weather}}</p>",
  controllerAs: 'vm',
  controller: function WeatherController($scope, weatherService, $element, $attrs) {
      var apikey = "b441194a96d8642f1609a75c1441793f";
      var city = "London";
      var controller = $scope;
      controller.weather = "None";
      weatherService.getWeather(apikey, city).then(function(response) {
          controller.weather = response.weather[0].description;
      });
  }
});
 ```

【讨论】:

    猜你喜欢
    • 2021-03-27
    • 1970-01-01
    • 1970-01-01
    • 2020-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-16
    • 2021-01-05
    相关资源
    最近更新 更多