2b2a 2b2a - 8 days ago 5
AngularJS Question

Angular "Cannot read property 'then' of undefined" with promise

I am stuck on why my promises aren't working. From the other articles I have looked at, I think I am doing it correctly. Here is the code I have currently:

Factory code

factory.isLoggedIn = function() {
$http.get('/api/v1/fitbit/auth')
.success((data) => {
return data.status;
})
.error((error) => {
console.log('Error: ' + error);
});
}


Controller code

$scope.fitbitAuth = function() {
FitbitFactory.isLoggedIn()
.then(
function(data) {
$scope.fitbitStatus = data;
},
function(errorData) {
console.log(errorData);
});
return $scope.fitbitStatus;
};


From my understanding of promises, the
return $scope.fitbitStatus
should be populating the
$scope.fitbitAuth
, but it isn't. I am also returning a boolean in the Factory, which should be populating
$scope.fitbitStatus
.

Answer

You have to return something (the promise), or it is undefined.

Factory code:

factory.isLoggedIn = function() {
  return $http.get('/api/v1/fitbit/auth');
}

Controller code:

$scope.fitbitAuth = function() {
    return FitbitFactory.isLoggedIn()
        .then(
            function(data) {
                $scope.fitbitStatus = data;
            },
            function(errorData) {
                console.log(errorData);
            });

};

The complete success/error block in your factory is not necessary and should be removed. I'm also unsure why you return $scope.fitbitStatus;.

Edit: Edited the answer to actually return the promise.

Comments