0

I am trying to use a service to access the current user variable from another controller. Here is my code:

Service:

angular.module('app').factory('AuthService', function ($http) {
  var currentUser;
});

Controller 1:

angular.module('app').controller('Signup', function ($scope, AuthService) {
  AuthService.currentUser = "[email protected]"
});

Controller 2:

angular.module('app').controller('Login', function ($scope, AuthService) {
  $scope.user = AuthService.currentUser;
});

View:

<body ng-controller="Login" ng-cloak>
  <button class="btn btn-link navbar-btn pull-right">{{user}}</button>
</body>

From looking at dev tools within chrome I can see that "user" is undefined. Any thoughts?

2 Answers 2

3

A factory is supposed to return a function or object that constitutes the service. Your factory defines a local variable, and doesn't return anything. So the service is, actually, undefined.

It should be:

angular.module('app').factory('AuthService', function () {
  return {
    currentUser: null;
  }
});
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for the answer. In the real application (I slimmed it down to highlight the issue) this is not working for me. I believe the problem is related to nested scoping. In other words, I don't think currentUser is populated yet when my app looks for it. Here's the full code of my app if you would be so kind to look at it.
Your answer combined with this SO question resolved the issue. stackoverflow.com/questions/15380140/…
1

Change the service is as below. The problem occurs because the variable in question is not visible. To expose data you should return an object containing all the methods and variables you want to share . Just be CAREFUL! It is a good practice to share variables. Use get and set methods for that. Directly to the variable behavior can lead to problematic as the system grows.

angular.module('app').factory('AuthService', function ($http) {
   var currentUser = "";
   return {
       setUser : function(user){
           currentUser = user;
       },
       getUser : function(){
           return currentUser;
       }
   };
});

2 Comments

Introducing such get/set methods will result in multiple currentUser objects, I dont think this is good.
Imagine the situation seguite whenever the user is setted should be turned a routine to validate the access permission . Before you set the value , you run a method to perform the validation. If you direct access to the variable it will be necessary to duplicate the validation routine before each call . I say it is not a bo practice because the responsibility for maintaining the user control should be in service. The ideal and perfect would be to create a module part to control the current user . A AppUserCurrent for example.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.