繁体   English   中英

无法读取Angular中未定义的属性'then'

[英]Cannot read property 'then' of undefined in Angular

我四处搜索,我认为我的代码是正确的,但是由于某种原因它仍然失败。

我的控制器:

$scope.unsubscribe = function()
  {
    bluetoothFactory.unsubscribe().then(function()
    {
      $scope.info = 'unsubscribe success';
    }, 
    function(error) 
    { 
      $scope.error = error;
    });
  };

我的工厂:

unsubscribe: function() {
      var q = $q.defer();
      $window.bluetoothSerial.unsubscribe().then(function (){
        q.resolve();
      }, function(error) {
        q.reject(error);
      });
      return q.promise();
    }

从我的控制器中,我只是调用:$ scope.unsubscribe()并收到此错误:

TypeError: Cannot read property 'then' of undefined
    at Object.unsubscribe (bluetoothFactory.js:37)
    at Scope.$scope.unsubscribe (bluetoothController.js:84)
    at Scope.$scope.submitReads (bluetoothController.js:118)
    at $parseFunctionCall (ionic.bundle.js:21044)
    at ionic.bundle.js:53458
    at Scope.$eval (ionic.bundle.js:23100)
    at Scope.$apply (ionic.bundle.js:23199)
    at HTMLButtonElement.<anonymous> (ionic.bundle.js:53457)
    at HTMLButtonElement.m.event.dispatch (jquery.js:4670)
    at HTMLButtonElement.r.handle (jquery.js:4338)

我的代码有什么问题?

如果我需要在数据到达控制器之前对其进行一些处理,我只会包装Promise。 你不是在这里 如果$window.bluetoothSerial已经返回一个诺言,则您不会通过将其包装在另一个诺言中来增加任何价值。

另一件事是Angular $q deferred s与jQuery deferred s有点不同。 要返回承诺,请使用return q.promise而不是return q.promise()

您的工厂实际上并没有做任何事情,因此您可以采用以下几种方法:

unsubscribe: $window.bluetoothSerial.unsubscribe

要么

unsubscribe: function() { return $window.bluetoothSerial.unsubsribe(); }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM