I am trying to write a factory that provides a simple user API. I'm new to AngularJS, and I'm a little confused about the factories and how to use them. I have seen other topics, but none of them are suitable for my use.
For simplicity, the only functionality I would like to get is to get all the users in the array and then pass them to the controller through the factory entered.
I saved the users in a json file (now I only want to read this file without changing the data)
users.json:
[ { "id": 1, "name": "user1", "email": " a@b.c " }, { "id": 2, "name": "user2", "email": " b@b.c " } ]
factory I'm trying to write should be something like this:
UsersFactory:
app.factory('usersFactory', ['$http', function ($http) { return { getAllUsers: function() { return $http.get('users.json').then( function(result) { return result.data; }, function(error) { console.log(error); } ); } }; }]);
And finally, the controller call will be like this:
UsersController
app.controller('UsersCtrl', ['$scope', 'usersFactory', function($scope, usersFactory){ usersFactory.getAllUsers().then(function (result) { $scope.users = result; }); }]);
I searched on the Internet, and it seems like it is not a good practice to use factories in this way, and if I would like to get some more features like adding / removing a new user to / from a data source, or in some way save the array in factory, this will not be the way to do this. I saw some places where using factory is like new UsersFactory() .
What would be the correct way to use factories when trying to use the API?
Is it possible to initialize a factory with an object containing the result of $http.get() , and then use it from the controller in this way?
var usersFactory = new UsersFactory();