B
B
boozzd2014-09-28 15:52:20
JavaScript
boozzd, 2014-09-28 15:52:20

How to listen in a directive for changes in a service (Angular js)?

There is a service that is responsible for authorization:

function AuthService($http, ipCookie, $location){
       return {
        auth: auth,
        isAuth: isAuth,
        logout: logout
       }
       function auth(credentials, callback){
        $http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded; charset=utf-8";
        $http({
            method: 'post',
            url: '/rest/?route=user/login',
            data: {'name': credentials.login, 'password': credentials.password}
        }).success(Success);
        
        function Success(data){
            if(angular.isObject(data)){
                ipCookie('login',data);
            }
                callback(ipCookie('login'));
        }
    }
    function isAuth(){
        var trigg = (ipCookie('login') === undefined) ? false : ipCookie('login');
        return trigg;
    }
    function logout(){
        $http({
            method: "post",
            url: '/rest/?route=user/logout'
        }).success(Success);
        function Success(data){
            if(data == 0){
                ipCookie.remove('login');
                $location.path('login');
            }
        }
    }
}

and there is a directive for the menu:
function navbarDirective(auth){
    var elements = '<div class="navbar navbar-default" role="navigation" ng-show="menuShow">'+
        '</div>';
    return {
        restrict: 'EA',
        template: elements,
        link: function(scope, element, attrs){
            scope.$watch(function(scope){
                if(auth.isAuth()) {
                    scope.menuShow = true;
                    scope.credentials = auth.isAuth();
                }else{
                    scope.menuShow = false;
                }
            });
            scope.logout = function(){
                auth.logout();
            }
        }
    }
}

How can I hide the menu or show when I am logged in or logged out? I will be glad to any criticism of this code.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey, 2014-09-28
@boozzd

For this it is better to use events. They will work instantly, they are not tied to $digest cycles, etc. Sculpting for this good bindings is unreasonably large overhead. In general, if we are talking about notification of a state change globally, then it is better to simply emit an event in $rootScope that will propagate down to all children.
ps why don't you use promises? instead of

myService.auth(data, function () {
    alert('success');
});

you can do like this:
myService.auth(data).then(function () {
});

this gives you a lot of possibilities. You can wedge into chains of promises, you can wait until several parallel requests complete. You can modify the data by means of a chain of promises:
myService.auth().then(function (userId) {
    return user.get(userId);
}).then(function (user) {
    // тут можно чего с пользователем поделать
    return user.friends;
}).then(function (friends) {
   if( !friends.length) {
        return $q.reject('У вас 0 друзей :(');
   }
   return $q.all(friends.map(function (user) {
        profile.get(user.id);
   });
}).then(function (friendsProfiles) {
    $scope.friends = friendsProfiles;
}, function (error) {
     alert(error);
});

I hope I have explained the possibilities clearly. The $http service and almost all services in Angular return promises. Forget stupid callbacks.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question