0

My task is to display the weather forecast from the API.

I have the following code, but I cannot get the data to show. I just started learning AngularJS and using APIs today, so any sort of help would be much appreciated! Specifically, what is wrong with my code that the weather data will not show?

This is the API I need to use:

 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>

Update

Solved the problem at hand. Thanks to all

9
  • 3
    what is your question? you posted a description of your project, a link to an API, and a bunch of code, but no problem statement. Commented Oct 29, 2015 at 0:53
  • Also, I doubt that your question involves the science and theories behind programming, so the computer-science tag is probably out of place. Commented Oct 29, 2015 at 0:55
  • try using $http.get() instead of $http.jsonp(). Url shown works fine with a get request Commented Oct 29, 2015 at 0:59
  • I'm sorry Claies. My question is what is going on in my JS code that isn't showing the data from the openweather API. Commented Oct 29, 2015 at 1:00
  • It's still not showing with .get() Commented Oct 29, 2015 at 1:01

3 Answers 3

1

You are using $http the wrong way. Is better and cleaner to create a request object and put the params there. Please here is the oficial docs: https://docs.angularjs.org/api/ng/service/$http#usage

And here 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>

Sign up to request clarification or add additional context in comments.

1 Comment

I am currently refreshing my front-end skills (I am a back-end dev) - I really appreciate you showing a 'better' way of retrieving API data in AngularJS.
1

You can use a factory or service for getting the information and then pass the information to the controller.

.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,
  };
}
}])

Then in your controller

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

With this you can access any data from the json file and display it in your view.

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

3 Comments

Please stop creating promises where you don't need, people is learning the wrong way.
@LeandroZubrezki why creating a promise is not required here?
$http is already a promise, you just need to return that promise. return $http.get('') .then(function(data){ return data; }) .catch(function(err){ return $q.reject(err); });
-1

Check this for ionic 4 App that use openWeather API http://www.offlineprogrammer.com/building-a-pwa-with-ionic-4-capacitor-temperature-city/

1 Comment

While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.