I've read several threads about angularjs services and factories. I understand that services are singletons and factories return instances of objects. But I still don't really understand how to use them. My app is a simple social network. The person using the app needs to log in, then they can view other members and send them messages.
My ideal design would be:
- Create a Member object to represent an arbitrary member of my service. Whenever a 'list' or 'get' operation returns data, it'd be wrapped in this member so I could call utility methods on it. I'd use a factory for this.
- When a user logs in to the app, create a Member to represent them (containing their userID and auth token for future authenticated requests). This must be available to other scopes, so could either be attached to the $rootScope, or be a MemberService that returns an instance of a Member tailored to the authenticated user.
I have created the following:
angular.module('myapp.models', [])
.factory('Member', ['$log', 'DataService', '$http', 'Restangular',
function($log, DataService, $http, Restangular) {
return {
user_id: null,
first_name: null,
last_name: null,
authenticate: function(username, password, loginSuccessHandler, loginErrorHandler) {
$log.debug("inside Member.authenticate");
var authSuccessHandler = function(data, status, headers, config) {
$http.defaults.headers.common.Authorization = 'Basic ' + btoa(data._id + ':' + data.token);
var token = btoa(data._id + ':' + data.token);
user_id = data._id; // attach this to the rootScope? Needs to be
// globally accessible (or even this whole object)
Restangular.setDefaultHeaders({'Authorization': 'Basic ' + token});
$log.debug("Auth successful, token stored " + token);
loginSuccessHandler();
};
DataService.authenticate(username, password, authSuccessHandler, authErrorHandler);
},
...
How can I instantiate this and make it available to other scopes (e.g. so in other scopes I'd know the logged in user's ID)?
Also, how could I instantiate this object when I'm parsing a list of members? E.g. if I have an object {first_name: "John", last_name: "Smith"}
how could I get a Member object from this factory with these attributes set?