Thomas CEDRINI Thomas CEDRINI - 9 months ago 28
AngularJS Question

Angular factory, how to completely change result

I am currently working on Angular and bump into an issue with factories and user login/logout.

Here is an example showing a use case :

An angular application supports user login and logout, as long as user is logged in, it is required the user's messages are loaded inside a MessageList (which is a factory). At first though, I set up an event system to trigger load/reset user messages if the user login or logout from the application. Here is the factory in code :

angular.module("Foo").factory("MessageList", MessageList);

MessageList.$inject = ["User"];

function MessageList(User) {
var _messages;

User.onLogin(activate); User.onLogout(function() { _messages = undefined; });

activate();
return _messages;

///

function activate() {
_messages = $http(...);
}

}


Angular factories are singleton, so execute only once. I already noticed it is possible to update some properties of an object (example
_messages.push
will properly return the message list with the new object in angular components depending on
MessageList
). But replacing the whole object does not seem to work (each time
onLogin
or
onLogout
is triggered, I need to completely rewrite
the _messages
object).

Answer Source

You can modify your logic like below to achive it:

angular.module("Foo").factory("MessageList", MessageList);

MessageList.$inject = ["User"];

function MessageList(User) {
    var _messages;

    User.onLogin(activate);       User.onLogout(function() { _messages = undefined; });

    function activate() {
        _messages.data = $http(...);
    }
    var _messages = {
        activate: activate
    };
    activate();
    return _messages;

}

Now the user details will be in the data property of the factories return object. Every time a new user logins, you can overwrite the data property alone.