When to Use Factory AngularJS

2

Hello everyone, good night,

I wanted to know two things the first is when I should use the factory directive and the other is if for example inside a factory I can make an Ajax request and return the result of it in a method of my factory, someone would have a example of this?

    
asked by anonymous 20.02.2015 / 03:53

1 answer

2

Using factory is one of the ways to create services with Angularjs. In addition to factory, you can use service and provider. All three variants have significant differences ( link ), however they all create a singleton service in your angularjs application.

Yes, it is possible and very common to encapsulate ajax calls within a service, see the example below:

app.factory('myService', function ($http) {
    var getData = function () {
      return $http.get("api/getdata/");
   };
    return getData; // note que factory deve ter um retorno
});
    
20.02.2015 / 18:04