0

I have a factory called Auth with a method Auth.signIn() that authenticates through my decoupled API. That part works, and I'm trying to capture the response which is the User information. Calling the factory from my controller works, but I can't seem to capture the response of the method.

controller

.controller('DashCtrl', function($scope, Auth) {
  //OAUTH SIGN IN
  $scope.signIn = function() {
    $scope.currentUser = Auth.signIn()
    //^^Auth.signIn() is happening but $scope.currentUser is undefined when I try to access it in the view
  }
  //OAUTH SIGN OUT
  $scope.signOut = function() {
    Auth.signOut()
  }

})

factory

.factory('Auth', function($auth) {
  var user = null
  return {
    signIn: function() {
      $auth.authenticate('google')
      .then(function(response) {
        return response //trying to catch this in the controller with currentUser = Auth.signIn()
        //verified that response is the user data
      })
      .catch(function(resp) {
        // handle errors
      })
    }
})

I'm new to angular so any help and pointers would be appreciated. I'm trying to be as concise as possible with my code/questions. Thank you in advance for helping.

1 Answer 1

1

Firstly, in your factory's signIn function, you should return the promise

signIn: function() {
      return $auth.authenticate('google')
      .then(function(response) {
        return response.data;
      });
    }

Then in your controller, chain the currentUser initialization after Auth.signIn

$scope.signIn = function() {
    Auth.signIn().then(function(data) {
      $scope.currentUser = data;
    }
  }
6
  • Thank you, this is exactly what I was looking for. As I mentioned in the other comment I grasp this deferred promises concept, but working around that in my code is still new. I'm going to test this out now. Feb 15, 2015 at 6:51
  • Personally I prefer promise chain, which is more common and easier to understand than callbacks.
    – Rebornix
    Feb 15, 2015 at 6:53
  • I'm using {{currentUser.name}} in the view, but it's not resolving to anything. Is that because the view is rendering before currentUser.name is resolved? Feb 15, 2015 at 6:54
  • 1
    $scope.currentUser is initialized only after signIn function is called. you can hide it by <div ng-if="currentUser">{{currentUser.name}}</div>, then it won't show until it's initialized.
    – Rebornix
    Feb 15, 2015 at 6:58
  • THANK YOU. FWIW mentioning, in the factory it's just response instead of response.data but that's just depended on my specific api's return . Live in the Bay Area by chance? I'll buy you a beer. I spent way too long in this rabbit hole. Feb 15, 2015 at 7:15

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.