Angular "Cannot read property 'then' of undefined" 承诺

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

我对为什么我的承诺不起作用感到困惑。从我看过的其他文章来看,我认为我做的是正确的。这是我目前的代码:

工厂代码

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

控制器代码

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

根据我对承诺的理解,return $scope.fitbitStatus 应该填充 $scope.fitbitAuth,但事实并非如此。我还在工厂中返回一个布尔值,它应该填充 $scope.fitbitStatus.

目前您还没有 return 来自 isLoggedIn 工厂方法的任何东西,您正在对其调用 .then 方法。

让它工作 return $http promiseobject from service method. In your case you could simply return$http.getmethod call which return promise object itself and then you can easily chain them up by callingFitbitFactory.isLoggedIn().then`

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

你必须return一些东西(承诺),否则就是undefined

工厂代码:

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

控制器代码:

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

};

工厂中完整的 success/error 块不是必需的,应将其删除。我也不确定你为什么 return $scope.fitbitStatus; 因为它在 return 时是未定义的。

编辑:编辑了实际 return 承诺的答案。