0

In my app, I want to create a service that looks in the backend to check if a user is logged in and returns the user data and privileges. My factory service looks like this:

app.factory 'Session', ['$http', ($http) ->
  getSession: ->
    $http.get("/admin/session")
]

Right now, I handle success and errors for the service in my controller shown below.

$scope.session = Session.getSession()
  .success((data) ->
    # Set the logged in user
    $scope.admin = data

    # Limit any privileges         
  )
  .error((data) ->
    # Logged in user not found so rediret to login screen
    window.location = "/user/login"
  )

My problem is that I need to repeat that same code in a lot of different controllers. Is there a better way to handle this? I am thinking I might need to do something with $rootScope but I do not understand how that works.

7
  • It is not clear what you are asking... Commented Aug 18, 2014 at 16:59
  • I want to know if there is a more efficient way of accomplishing this so I don't have to repeat all of this code in every controller. Basically, I want the controller to be able to get the logged in user from the service. If it fails, I want the service to tell the page to redirect to the login screen. I don't want to have to handle the success and error of the promise in every controller. Commented Aug 18, 2014 at 17:03
  • 1
    Could you just handle the error in your service instead? Commented Aug 18, 2014 at 17:07
  • 1
    Could you please show what you have tried? It should be able to just chain the .error() in your service. Commented Aug 18, 2014 at 17:16
  • 1
    Do you want to repeat the $http.get("/admin/session") for each individual controller? Shouldn't you run this only once? Commented Aug 18, 2014 at 17:24

1 Answer 1

1

You can put the logic inside service itself. You will have to use promises for returning success data to the controller. So for controller, it will be something like this:

   Session.getSession().then(function(data){
      $scope.admin = data;
   });

And you will handle your errors in service. Note that this is pseudo code.

app.factory 'Session', ['$http', ($http) ->
  getSession: ->
    return $http.get("/admin/session")
           .success(data){}
           .error(){ //... redirect user}
]
Sign up to request clarification or add additional context in comments.

3 Comments

There is no need to create another promise using $q.defer(), you could just chain the error callback and return the original promise.
Do you mean something like this? return $http.get().success(//handle success logic).error(// handle error);
Yes, that what I mean.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.