When to Use Factory Angularjs

Asked

Viewed 426 times

2

Hello folks 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 within a Factory I can make an Ajax request and return the result of it in a method of that my Factory, someone would have an example of this?

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. The three variants have significant differences(https://docs.angularjs.org/guide/providers), but all create a Singleton service in your 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
});

Browser other questions tagged

You are not signed in. Login or sign up in order to post.