AngularJs错误:无法读取未定义的属性'then'

3

这是模块

(function(){

    /**
    * app Module
    *
    * Description
    */
    angular.module('app',[]);
})();

I have this service

(function(){
    'use strict';

angular
    .module('app')
    .factory('homeservice',homeservice);

homeservice.$inject = ['$http']

function homeservice($http){

    var service = {
        test : test
    }
    return service;

    /**
     * get articles
     * @return {[type]} [description]
     */
    function test(){
      $http.get('/test')
         .then(testSuccess)
         .catch(testError)

      function testSuccess(response){
         return response.data;
         //console.log(response.data) this line prints data to console
      }

      function testError(error){
         return error;
      }
    }
}
})();

这是我的控制器,调用函数。
(function(){


angular.module('app')
       .controller('HomeController',HomeController);

    HomeController.$inject = ['homeservice']
    function HomeController(homeservice) {
        var vm = this;

        test();

        function test(){
             homeservice.test().then(function(response){
                console.log(response);
            });
        }

    }
    })();

我在调用控制器中的方法时一直收到错误消息 - 无法读取未定义的属性'then'。我之前使用过这种方式,它可以正常工作。 答案
function test(){
          return $http.get('/test') // return was missing here
             .then(testSuccess)
             .catch(testError)

          function testSuccess(response){
             return response.data;
             //console.log(response.data) this line prints data to console
          }

          function testError(error){
             return error;
          }
        }

我在$http.get('/test')处遗漏了return


你定义了这个模块吗? - Sajeetharan
@Sajeetharan 是的,模块已经定义了,忘记添加它了。 - trying to learn
4个回答

4
这是一个HTML标签。
homeservice.test().then(function(response){ ... });

假设test方法应该返回一个promise。但是它返回了undefined,这就是错误的原因。

正确的写法应该是:

/**
 * get articles
 * @return {[type]} [description]
 */
function test(){
  return $http.get('/test')
     .then(testSuccess)
     .catch(testError)

  ...
}

当我从工厂中使用console.log响应时,它会将数据输出到控制台。但是控制器会抛出错误。 - trying to learn
不确定您的意思。问题中的代码缺少return语句,这就是为什么会出现Cannot read property 'then' of undefined错误的原因。如果您在应用此答案后仍然遇到错误,请提供一个plunk,以便可以复制该问题。 - Estus Flask

1
测试函数需要返回$http承诺:
function test(){
  ͟r͟e͟t͟u͟r͟n͟  $http.get('/test')
//^^^^^^ ---------------------RETURN the $http promise
     .then(testSuccess)
     .catch(testError)

  function testSuccess(response){
     return response.data;
  }

  function testError(error){
     ̶r̶e̶t̶u̶r̶n̶ ̶e̶r̶r̶o̶r̶;̶
     //throw to chain rejection
     throw error;
  }
}

在成功和错误处理程序中的`return`语句不会将值返回给父函数。在层次结构的每个级别上放置`return`语句。

针对较旧版本的AngularJS进行拒绝重新抛出

以前(版本<1.6),从promise的onFulfilledonRejection处理程序抛出的错误也会传递给$exceptionHandler()(除了将该错误作为原因拒绝该promise)。

为了避免在较旧版本中控制台出现错误消息,请通过返回一个被拒绝的promise来重新抛出:

  function onRejection(error){
     ̶r̶e̶t̶u̶r̶n̶ ̶e̶r̶r̶o̶r̶;̶
     console.log(error.status);
     //throw to chain rejection
     return $q.reject(error);
  }

对于初学者来说,一个常见的问题是被拒绝的承诺错误地转换为已完成的承诺。重要的是从拒绝处理程序中重新抛出错误。

另外,当函数省略返回语句时,该函数返回一个值undefined,这会错误地将拒绝转换为已完成的承诺,并解决一个值undefined

来自文档:

由于e13eea,从 promise 的 onFulfilled 或 onRejection 处理函数中抛出的错误与普通拒绝一样处理。以前,它也会传递到 $exceptionHandler()(除了将错误作为原因拒绝承诺)。— AngularJS 开发人员指南 - 迁移到 v1.6($q)

0

这不应该是:

$http.get('/test')
  .success(successFunction)
  .error(errorFunction);

至少对于版本 < 1.4.8

对于版本 > 1.4.8,请尝试以下操作:

$http.get('/test')
  .then(
    function(response) { }, // success
    function(response) { } // failure
  );

我正在使用AngularJs版本1.6.0,但即使我尝试这个,它仍然会抛出另一个错误:**$http.get(...).success不是一个函数**。 - trying to learn
我已经更改了它,以包括> 1.4.8的语法,看看是否有任何变化。 - rrd
这并不能解决我的问题,因为我的逻辑是相同的。 - trying to learn
不应该。在1.4.8之前,success就已经被弃用了。 - Estus Flask

0
(function(){
    'use strict';

angular
    .module('app')
    .factory('homeservice',homeservice);

homeservice.$inject = ['$http']

function homeservice($http){
   return {
        test: function () {
            console.log("inside function");
            return $http.get('stats.json');
        }
    };
}
})();

演示


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接