【问题标题】:Angular TypeError: Cannot read property 'then' of undefinedAngular TypeError:无法读取未定义的属性“then”
【发布时间】:2014-11-29 02:14:53
【问题描述】:

我有这样的数据服务:

this.myFunction= function(callback) {
    var url = rootURL + "path1/path2/service.json";
    var promise = $http.get(url);
    promise.then(function(payload){
        return callback(payload); 
    });
    return promise; 
}

在控制器中调用它来初始化一些东西:

DataService.myFunction(function(data) { 
    if(data.statusText !== "OK"){
        $scope.$worked= false; 
    }else{  
        $scope.$worked= true;               
    }
}

我得到“TypeError:无法读取未定义的属性'then'”。回调中的 Console.log(data) 显示 200“OK”响应和我期望的数据。我已经搜索过这个错误,主要是由于没有在服务中返回承诺。但是,我要兑现承诺。在回调中对控制器范围设置任何内容都会导致错误。

Angular 版本:AngularJS v1.3.0-rc.2

谢谢!

【问题讨论】:

  • 可以发一下回调函数吗?此外,无需将 get 分配给一个变量,它已经是一个承诺,您只需调用 .then 就可以了。
  • 你能提供一个 plunkr 或更多的上下文吗?看来该代码不应抛出该 TypeError。

标签: angularjs


【解决方案1】:

在这种情况下,您不需要返回承诺,因为您使用的是回调。回调和承诺是频谱的两端。有了这个,你就可以完成你想要的。

如果你想使用回调,你可以留下你的控制器代码。

this.myFunction= function(callback) {
    var url = rootURL + "path1/path2/service.json";
    $http.get(url).then(function(response) {
        callback(response.data);
    });
}

或者如果你想利用承诺

this.myFunction= function() {
    var url = rootURL + "path1/path2/service.json";
    return $http.get(url).then(function(response) {
        return response.data;
    });
}

DataService.myFunction().then(function(data) { 
    if(data.statusText !== "OK"){
        $scope.$worked = false; 
    } else {  
        $scope.$worked = true;               
    }
});

【讨论】:

  • +1 以获得更好的回调处理方式。我实际上发现我的应用程序包含来自另一个版本(v1.2.20)的“ngAnimate”。我不再需要它,所以我把它拿出来,突然之间不再出现类型错误。
  • 我有一个带有$http 调用和.then(function(res){return res;}); 的服务,并从我有serviceName.functionName().then(function(res){//do something with res}) 的控制器调用它,但我一直收到Cannot read property 'then' of undefined,尽管它以前工作过......什么可能是什么原因?
猜你喜欢
  • 2019-08-19
  • 2014-09-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-11-26
  • 2016-09-20
  • 1970-01-01
相关资源
最近更新 更多