PDN
PDN

Reputation: 791

AngularJS: How to update service properties while keeping logic in controller?

A typical service might look like this:

(function() {
    angular.module('module').service('SomeService', SomeService);

    SomeService.$inject = ['$http'];

    function SomeService($http) {
        var service = {
            login: login,
            logout: logout,
            userState: null //object for logged in status, points etc (is there a convention for what to initialize this to?)
        }

        return service;

        login(){ //$http implementation }
        logout(){ //implementation }
    }
})();

It makes sense that login would modify userState, but how can I do that from within the service. Since login is hoisted to the top of SomeService constructor, it will not have access to service.userState. The alternative would be to place logic to modify userState in the controller... In other words, return the $http login promise and then have the controller set the userState with SomeService.user.loggedIn = true, but would that be considered bad since now the controller determines whether or not the user is logged in? Shouldn't that logic belong in the service instead?

One thing I can think of are to use function expressions / IIFE - I don't want to do this since that involves bringing implementation details to the top of the file.

Upvotes: 0

Views: 32

Answers (1)

Zhiliang Xing
Zhiliang Xing

Reputation: 1057

if you don't want userState to be edited out of the service, you just need a getter function to get the value if my understanding is correct.

(function() { angular.module('module').service('SomeService', SomeService);

SomeService.$inject = ['$http'];

function SomeService($http) {
    var userState = null;
    var service = {
        login: login,
        logout: logout,
        getUserState: getUserState
    }

    return service;

    function login(){ //$http implementation and you can use $promise to change userState to true here }
    function logout(){ //implementation and you can use $promise to change userState to null here }
    function getUserState(){ return userState; }
}

})();

Upvotes: 1

Related Questions