Javascript 无法读取属性';然后';在角度上未定义的
我已经到处搜索过了,我认为我的代码是正确的,但由于某些原因它仍然失败 我的控制器:Javascript 无法读取属性';然后';在角度上未定义的,javascript,angularjs,Javascript,Angularjs,我已经到处搜索过了,我认为我的代码是正确的,但由于某些原因它仍然失败 我的控制器: $scope.unsubscribe = function() { bluetoothFactory.unsubscribe().then(function() { $scope.info = 'unsubscribe success'; }, function(error) { $scope.error = error; });
$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)
TypeError:无法读取未定义的属性“then”
在Object.unsubscribe(bluetoothFactory.js:37)
在Scope.$Scope.unsubscribe(bluetoothController.js:84)
范围为$Scope.submitrades(bluetoothController.js:118)
at$parseFunctionCall(ionic.bundle.js:21044)
在爱奥尼亚.邦德.js:53458
范围$eval(IONAL.bundle.js:23100)
在范围内$apply(IONAL.bundle.js:23199)
在HTMLButtoneElement。(ionic.bundle.js:53457)
在HTMLButtonElement.m.event.dispatch(jquery.js:4670)
位于HTMLButtonElement.r.handle(jquery.js:4338)
我的代码有什么问题?只有在数据到达控制器之前需要对其进行一些处理时,我才会包装承诺。你不是在这里这样做的。如果
$window.bluetoothSerial
已经返回了一个承诺,那么您不会通过将其包装在另一个承诺中来增加任何价值
另一件事是Angular$q
deferred
s与jQuerydeferred
s稍有不同。要返回承诺,请使用return q.promise
而不是return q.promise()
你的工厂实际上什么都不做,所以你可以用两种方法来做:
unsubscribe: $window.bluetoothSerial.unsubscribe
或
有点奇怪,您在这里没有得到错误:
返回q.promise()代码>promise
应该返回,而不是执行。似乎$window.bluetoothSerial.unsubscribe()
没有返回承诺。你能把那部分代码添加到问题中吗?@KevinB也是正确的-你应该返回q.$promise
而不是q.promise()
。哦,因为你还没有到达那一行。:)这将是下一个问题。问题在于bluetoothSerial
的unsubscribe
方法。如何更改我的代码以不返回第二个承诺?我删除了()并且它仍然不工作。我想这是双重承诺。我怎样才能摆脱这个呢?我完全取消了承诺,而且效果很好。
unsubscribe: function() { return $window.bluetoothSerial.unsubsribe(); }