使用AngularJS和OpenWeather创建天气应用程序

时间:2015-10-29 00:51:13

标签: javascript angularjs api ionic-framework

我的任务是从API显示天气预报。

我有以下代码,但我无法显示数据。我刚刚开始学习AngularJS并使用API​​,所以我们非常感谢任何帮助!具体来说,我的代码有什么问题,天气数据不会显示?

这是我需要使用的API:

 http://api.openweathermap.org/data/2.5/forecast/daily?q=KansasCity&mode=json&units=imperial&cnt=7&appid=bd82977b86bf27fb59a04b61b657fb6f

 angular.module('starter', ['ionic'])

.run(function($ionicPlatform) {
  $ionicPlatform.ready(function() {
    // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
    // for form inputs)
    if(window.cordova && window.cordova.plugins.Keyboard) {
      cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
    }
    if(window.StatusBar) {
      StatusBar.styleDefault();
    }
  });
})

.controller('OpenWeather', function($scope, $http, $log) {
    $scope.city = "Kansas City";
    $scope.units = 'imperial';

    $scope.change = function() {
        var url = 'http://api.openweathermap.org/data/2.5/forecast/daily?q=KansasCity&mode=json&units=imperial&cnt=7&appid=bd82977b86bf27fb59a04b61b657fb6f';
        $http.jsonp(url)
        .success(function(data, status, headers, config) {
            $scope.main = data.main;
            $scope.wind = data.wind;
            $scope.description = data.weather[0].description;
        })
        .error(function(data, status, headers, config) {
            $log.error('Could not retrieve data');
        });
    };

    $scope.change();
});

 <!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
    <title>Weather App</title>

    <link href="lib/ionic/css/ionic.css" rel="stylesheet">
    <link href="css/style.css" rel="stylesheet">

    <!-- IF using Sass (run gulp sass first), then uncomment below and remove the CSS includes above
    <link href="css/ionic.app.css" rel="stylesheet">
    -->

    <!-- ionic/angularjs js -->
    <script src="lib/ionic/js/ionic.bundle.js"></script>

    <!-- cordova script (this will be a 404 during development) -->
    <script src="cordova.js"></script>

    <!-- your app's js -->
    <script src="js/app.js"></script>
  </head>
  <body ng-app="starter" ng-controller="OpenWeather">
    <ion-pane>
      <ion-header-bar class="bar-positive">
        <h1 class="title">Kansas City Weather</h1>
      </ion-header-bar>
      <ion-content>
          <div class="list card">
              <div class="item item-avatar">
                <img src="img/ionic.png">
                <h2>10 Day Forecast</h2>
                <p>Kansas City, MO</p>
              </div>
              <div class="item item-avatar">
                  <h3>{{data.name}}</h3>
                  <p>Temp: {{main.temp}}</p>
                  <p>
              </div>
              </div>
      </ion-content>
    </ion-pane>
  </body>
</html>

更新

解决了手头的问题。感谢所有

3 个答案:

答案 0 :(得分:2)

您可以使用工厂或服务获取信息,然后将信息传递给控制器​​。

.factory('weatherService', ['$http', '$q', function ($http, $q){
function getWeather () {
    var deferred = $q.defer();
    $http.get('http://api.openweathermap.org/data/2.5/forecast/daily?q=KansasCity&mode=json&units=imperial&cnt=7&appid=bd82977b86bf27fb59a04b61b657fb6f')
      .success(function(data){
        deferred.resolve(data);
      })
      .error(function(err){
        deferred.reject(err);
      });
    return deferred.promise
  }

  return {
    getWeather: getWeather,
  };
}
}])

然后在您的控制器中

.controller('OpenWeather', ['$scope', 'weatherService', function($scope, weatherService) {
weatherService.getWeather().then(function(data) {
      $scope.city = data;
})

使用此功能,您可以访问json文件中的任何数据并将其显示在视图中。

 <div class="item item-avatar">
    <h3>{{city.name}}</h3>
    <p>Temp: {{city.temp}}</p>
    <p>
</div>

答案 1 :(得分:1)

你正在以错误的方式使用$ http。 创建请求对象并将params放在那里更好更清晰。请在这里提供官方文档:https://docs.angularjs.org/api/ng/service/ $ http#usage

这里是JSBIN:http://jsbin.com/doqeselile/edit?html,css,js,output

var app = angular.module('jsbin', []);

app.controller('DemoCtrl', function($http) {
  
  var vm = this;
  
  var URL = 'http://api.openweathermap.org/data/2.5/forecast/daily';
  
  var request = {
    method: 'GET',
    url: URL,
    params: {
       q: 'KansasCity',
      mode: 'json',
      units: 'imperial',
      cnt: '7',
      appid: 'bd82977b86bf27fb59a04b61b657fb6f'
    }
  };
  
  $http(request)
    .then(function(response) {
      vm.data = response.data;
    }).
    catch(function(response) {
      vm.data = response.data;
    });
});
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Angular JS</title>
</head>
<body ng-app="jsbin">
  <div ng-controller="DemoCtrl as vm">
    <h1>{{ vm.data | json }}</h1>
  </div>
  <script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.7/angular.js"></script>
</body>
</html>

答案 2 :(得分:-1)

选中此项以检查使用openWeather API http://www.offlineprogrammer.com/building-a-pwa-with-ionic-4-capacitor-temperature-city/的ionic 4应用程序