0

I'm a bit confused with Angular. I have two factories, with code looks almost the same, because they performs CRUD operations on two different objects in db, and I want to make them DRY.

So I have idea to move common logic to separate service, and I want it to works something like that :

angular.module('app').factory('first',['commonService',function(commonService){
    return new commonService('someSpecificVariable');
}])

and service :

angular.module('app').service('commonService',['someDep1',function(someDep1,someSpecificVariable){
    var something = someSpecificVariable;
}]);

I looked at providers, but i need something to instantiate. How can I achieve this?

In another words I want create factory responsible for all crud operation requests for all app modules, because writing many factories just to handle http/crud don't looks ok for me.

Ok i descriped it quite bad.

SOLUTION Is it possible and in good form to reuse the same data factory in Angular?

Community
  • 1
  • 1
Sajgoniarz
  • 176
  • 13

2 Answers2

0

Factories

They let you share code between controllers as well as making http calls to your API. They are really about making some reusable code that you can instantiate in your controllers to make your life easier and your controllers cleaner.

Simple Example

.factory('FindFriend', function ($http, $rootScope) {
  return {
    find: function (phone) {
        return $http.get('http://130.211.90.249:3000/findFriend', { params: {phone:phone}})
    },
    add: function (id) {
        return $http.get('http://130.211.90.249:3000/addFriend', { params: {friendid:id, user_id: $rootScope.session} })
    },
    deleteFriend: function (id) {
        return $http.get('http://130.211.90.249:3000/deleteFriend', {params:{idfriends: id}})
    }
  }
})

Explanation

So above we can see a factory called FindFriend. The factory has 3 methods find add and delete. these are different http calls (in your code they shouldn't be all get methods but this is some old code I wrote).

They can be instantiated by adding them into the top of the controller and then calling there functions like FindFriend.add

Hope this sheds some light on factories for you.

Joe Lloyd
  • 19,471
  • 7
  • 53
  • 81
  • I would add an example of how to actually instantiate the factory rather then showing how to define a factory. – Stefan Sep 01 '17 at 13:16
-1

I know how factories works, but i dont want to add bunch of functions responsible for each module. I wish to make service, which will replace patches to $http calls based of provided module name in constructor. ex 'orders' will make request : $http.post('/api'+'orders'+'/lazy')...

Sajgoniarz
  • 176
  • 13