Sonu Kapoor
Sonu Kapoor

Reputation: 1637

Cannot read property 'then' of undefined in Angular

I have searched around and I think my code is correct, but for some reason its still failing.

My controller:

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

My factory:

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

From my controller I just call: $scope.unsubscribe() and receive this error:

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)

Whats wrong with my code?

Upvotes: 1

Views: 973

Answers (1)

Andy Gaskell
Andy Gaskell

Reputation: 31761

I only wrap promises if I need to do some processing on the data before it reaches the controller. You aren't doing that here. If $window.bluetoothSerial already returns a promise you aren't adding any value by wrapping it in another promise.

The other thing is that Angular $q deferreds are a little different than jQuery deferreds. To return a promise use return q.promise instead of return q.promise().

Your factory doesn't really do anything so you could do it a couple ways:

unsubscribe: $window.bluetoothSerial.unsubscribe

or

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

Upvotes: 1

Related Questions