Reputation: 49097
I am building an app with AngularJS and it is going well, but I have a problem with understanding where and how to code global stuff like the process of logging out for instance?
I have a link in the right upper corner that will remove the user cookies when clicked. There is probably a common approach for sharing the code of actual doing so? Do you set up a controller hierachy where you inherit actions? Do some broadcasting magic? Directive?
I need some help with how to do this.
Upvotes: 0
Views: 94
Reputation: 246
Use services. You could create a $user or $auth service which will do the actual login/logout and loading of current user info, permission checks etc. controllers an other services should use this service for doing user/auth related stuff.
This applys for other things as well. Like if you must share data or provide common APIs for controllers/directives to use.
Upvotes: 0
Reputation: 13918
You could define service - something like this:
app.service('Auth', function() {
var auth = {};
auth.loggedIn = false;
auth.login = function() {
auth.loggedIn = true;
};
auth.logout = function() {
auth.loggedIn = false;
};
return auth;
});
The above code sample is taken from article titled Consuming services which I highly recommend. By reading it you will get insight of how services can be used.
[Update]
I believe you have two options on how to use this service. You can use it one of the Controllers of you aplication (like it is us used in provided article) or you could create a reusable Directive.
There is JSFiddle demonstrating the first option where service is injected in top most controller and exposed trough top most scope. The child scopes prototypically inherits from parent scope so that's the reason that you can access the service also in child scopes.
Upvotes: 1
Reputation: 6711
There is an awesome article i came across yesterday outlining login stuff and angular:
https://medium.com/opinionated-angularjs/7bbf0346acec
But the short answer yes, I agree, it should be in a service - ie singleton.
Upvotes: 0