Learn
Services
Services I

So far we’ve made AngularJS apps by adding data to a controller, and then displaying it in a view.

But what happens when the data contains hundreds of items, or if it’s constantly changing like weather or financial data? Hardcoding data into a controller won’t work anymore.

A better solution is to read the live data from a server. We can do this by creating a service.

Instructions

1.

In the browser frame on the right, visit https://content.codecademy.com/courses/ltp4/forecast-api/forecast.json. It’s a JSON object containing a city_name and an array days containing weather data for the next five days.

2.

Create a service named forecast that fetches the weather data from the server. In the new file js/services/forecast.js. Type in this code exactly as you see here:

app.factory('forecast', ['$http', function($http) { return $http.get('https://content.codecademy.com/courses/ltp4/forecast-api/forecast.json') .success(function(data) { return data; }) .error(function(err) { return err; }); }]);
3.

Include js/services/forecast.js in index.html in line 61 as a new <script> element.

4.

In the controller, modify MainController by passing in the forecast service, like this:

app.controller('MainController', ['$scope', 'forecast', function($scope, forecast) { // ... }]);
5.

Inside MainController, use the forecast service to save the weather data into $scope.fiveDay, like this:

forecast.success(function(data) { $scope.fiveDay = data; });
Folder Icon

Take this course for free

Already have an account?