0

I'm doing the CA course for angular. Here is the code for the controller, in controller.js:

app.controller('MainController', ['$scope', 'forecast', function($scope, forecast) {
  forecast.success(function(data) {
    $scope.fiveDay = data;
  });
}]);

Here is the code for the service, in service.js:

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

So I guess factories are services? What exactly is a service? I saw this explanation but it isn't the most clear to me.

Services

Syntax: module.service( 'serviceName', function ); Result: When declaring serviceName as an injectable argument you will be provided with an instance of the function. In other words new FunctionYouPassedToService().

In the two code snippets, when is the service called? What is the forecast.service doing in the controller? What is forecast = in the controller? Is it an object?

Jwan622
  • 11,015
  • 21
  • 88
  • 181
  • You guess correctly. Maybe this thread will help clarify a few aspects: http://stackoverflow.com/questions/15666048/service-vs-provider-vs-factory – chris Jun 18 '15 at 14:11
  • https://docs.angularjs.org/guide/providers – JB Nizet Jun 18 '15 at 14:14
  • The docs I've seen already. What I gathered is that there is an injector service which creates objects. You register a recipe for the injector to create objects. There are 5 recipes: Providers, factories, service, value, and constant? – Jwan622 Jun 18 '15 at 14:37

2 Answers2

1

An Angular factory is a function which when called will return the service. The service can be pretty much anything. In your case, you are returning the result of $http(...).success(..).error(...) in your return statement which is a promise.

So when you instantiate the controller, the factory gets called, calls inside the function body the HTTP call and returns a promise.

In the controller you receive a promise object which you can call success or error on.

This way, you cannot repeat the HTTP call, since once factories are called, all other controller receive the same instance (in this case the HTTP call is made only when the first controller is instantiated with the forecast dependency, all other controllers with that dependency get the same promise for the already called HTTP request)

vvondra
  • 3,022
  • 1
  • 21
  • 34
0

try this

$http.get('//s3.amazonaws.com/codecademy-content/courses/ltp4/forecast-api/forecast.json') instead of $http.get('http://s3.amazonaws.com/codecademy-content/courses/ltp4/forecast-api/forecast.json')

helped to me.