Learn
Services
Services II
Well done! The city_name
now shows up in the view. How does it work?
- First in js/services/forecast.js, we made a new service. We used
app.factory
to create a new service namedforecast
- The
forecast
service needs to use AngularJS’s built-in$http
to fetch JSON from the server. Therefore, we add$http
to theforecast
service as a dependency, like this:
Now['$http', function($http) { // ... }]$http
is available to use insideforecast
. - Then, inside
forecast
, we use$http
to construct an HTTPGET
request for the weather data. If the request succeeds, the weather data is returned; otherwise the error info is returned. - Next in the controller, we used the
forecast
service to fetch data from the server. First we addedforecast
intoMainController
as a dependency so that it’s available to use. Then within the controller we usedforecast
to asynchronously fetch the weather data from the server and store it into$scope.fiveDay
- As before, any properties attached to
$scope
become available to use in the view. This means in index.html, we can display thecity_name
using an expression as done before.
Instructions
1.
In the browser, visit https://content.codecademy.com/courses/ltp4/forecast-api/forecast.json. Looking at the format of the data in the days
array, each day has four pieces of data - datetime
, icon
, high
, and low
.
2.
Visit http://localhost:8000 to view the AngularJS app. Let’s finish the view so that it displays the weather for each day.
Notice in the view, we’re using ng-repeat
to loop through each item in the days
array. Inside this loop, display a day’s four pieces of data.
Remember to use ng-src
to display an image.
3.
Use the date
filter to format the datetime
.