【问题标题】:Angular "Cannot read property 'then' of undefined" with promise带有承诺的Angular“无法读取未定义的属性'then'”
【发布时间】:2016-11-26 04:48:41
【问题描述】:

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

工厂代码

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

【问题讨论】:

  • 在 factory.isLoggedIn 的 $http 前添加 return 语句
  • 并摆脱工厂中的成功和错误。

标签: javascript angularjs promise es6-promise


【解决方案1】:

你必须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);
            });

};

工厂中的完整成功/错误块不是必需的,应该删除。我也不确定你为什么要return $scope.fitbitStatus;,因为它在返回时是未定义的。

编辑:编辑答案以实际返回承诺。

【讨论】:

  • 我返回了$scope.fitbitStatus,因为我正在查看的其他一些论坛建议返回承诺。不过,我可能,也可能是,我如何实现它是错误的。
  • 您返回的不是承诺,而是返回时未定义的东西。我编辑了答案。 @2b2a
  • @2b2a 看看我在控制器代码中将返回移动到了哪里。现在诺言被退回了。您返回的内容在您返回时将是未定义的
【解决方案2】:

目前你还没有从isLoggedIn工厂方法返回任何东西,你正在调用.then方法。

为了让它工作返回$httppromiseobject 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');
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-04-23
    • 2017-01-23
    • 2017-07-19
    • 1970-01-01
    • 2015-09-08
    • 2020-03-12
    • 2019-03-10
    • 2018-08-17
    相关资源
    最近更新 更多