Привет, я узнаю о angularjs. Я хочу получить ТЕМПЕР от одного json и отобразить это значение в моем компоненте. Я не знаю, что я делаю неправильно - PullRequest
0 голосов
/ 30 апреля 2020

Я учусь js Получить. Я пытаюсь получить значение temp из отклика и отобразить это значение в моем компоненте. 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', []);

URL-адрес ответа API: https://openweathermap.org/current


1 Ответ

0 голосов
/ 01 мая 2020
  1. Для получения элемента из json:

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

Способ решить эту проблему: создать сервис, чтобы я мог получить данные и изменить компонент. Я отказываюсь от идеи использовать "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;
      });
  }
});
 ```
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...