0

I have a fairly simple angular app (working off the MEAN stack) that is not using the ui-router (and I would like to keep it that way for right now).

I am wondering what the best way to share a users "logged in" status across the app is.

For instance, I would like a directive to show "Signup or Login" if the user is not logged in, or "Hello, username" if the user is logged in.

Throughout my app, many directives refer to the logged in status and so it seems that using multiple Controllers and declaring a logged in $scope property on each one is not the best idea. How could I achieve this?

As a follow up, any recommendations on the best way to know if a user is logged in or not? Right now I am basing it off an auth-token that is stored in local storage, but it could be cookies as well.

I would like to know a/the best practice way that I could store more than a user's logged in status but also their information (name, items picked out etc.) and keep it synced to my server (so if they log in on another computer, their cart would persist).

Thanks

Startec
  • 12,496
  • 23
  • 93
  • 160
  • Share the logged in boolean across the controllers with a factory. Simple example of factory data shared between controllers http://stackoverflow.com/a/21924873/1803298 – cheekybastard Feb 06 '15 at 02:32

1 Answers1

0

Write a service:

angular.module('myApp')
.service('Auth', function() {
    var loggedInState = {}; // log in state data

    var logIn = function() {
        // send log in request
    }

    return {
        state: loggedInState,
        logIn: logIn
    }
})

Now you inject this service everywhere you want to know if they were logged in, and check the state

Peter Ashwell
  • 4,292
  • 2
  • 18
  • 22
  • Okay, so then if I wanted to conditionally show or hide something in a directive, that has this injected, how do I do so. In other words, how do I access this `Auth` service's properties and set them as `$scope` in a directive once it is injected? – Startec Feb 06 '15 at 02:53
  • 1
    Inject the service in the controller, and assign the property you need from the service to the controllers scope, or the whole service if you prefer. – Peter Ashwell Feb 06 '15 at 02:54
  • Got it. I see, inject the controller into the `controller` property of the directive. – Startec Feb 06 '15 at 02:58
  • You inject the service into the controller, directive, whatever: .directive('header', function(Auth, newFactory) { ... } – Peter Ashwell Feb 06 '15 at 03:03
  • When I try this, returning an object for `loggedInState`, nothing appears in my template. However, if I enter an object directly in the return value, the values from that object do appear. Do you know why this is? – Startec Feb 06 '15 at 03:22
  • To clarify, I asked a separate question http://stackoverflow.com/questions/28358107/why-can-i-access-data-directly-returned-by-factory-but-not-through-a-declared-o – Startec Feb 06 '15 at 03:31