我是 Angular 的新手,在进行同步操作时遇到了问题。我已经解决了 Angular Controller 出现的几个问题,我从 newController 文件中得到错误“无法调用未定义的方法”。
angular.module('newApp.newController', ['angularSpinner', 'ui.bootstrap'])
.controller('newController', function($q, $scope, utilityFactory, $http) {
utilityFactory.getData().then(function(data) {
console.log("success");
console.log(data);
});
});
angular.module('newApp.utility', [])
.factory('utilityFactory', function($q, $http) {
var utils = {};
//This is a cordova plugin
var getLauncher = function() {
return window.plugin.launcher;
};
var success = function(data) {
console.log(device);
return device;
}
var fail = function(error) {
console.log("error", error);
};
utils.getData = function() {
/* Get the store number details initially before initalizing the application */
if (window.plugin) {
var launcher = getLauncher();
console.log("Fetching data from device");
//Cordova js is returning this method
return launcher.getDevice(success, fail);
}
};
return utils;
})
最佳答案
基于以下理解:
Launcher.prototype.getDevice = function(successCallback, failureCallback) {
exec(successCallback, failureCallback, KEY, 'getDevice', []);
}
,我们知道 window.plugin.launcher.getDevice()
返回 undefined
,而不是数据对象。相反,它通过成功/失败回调提供响应。
因此,要使用 promises,window.plugin.launcher.getDevice()
需要“promified”,包括显式创建 new Promise()
及其通过 .getDevice 回调的解决/拒绝。 (简单地包装在 $q(...) 中不是一回事,也行不通)。
angular.module('newApp.utility', []).factory('utilityFactory', function($q, $http) {
return {
getDevice: function() {
return $q.defer(function(resolve, reject) {
window.plugin.launcher.getDevice(resolve, reject); // If this line throws for whatever reason, it will be automatically caught internally by Promise, and `reject(error)` will be called. Therefore you needn't explicitly fork for cases where `window.plugin` or `window.plugin.launcher` doesn't exist.
}).promise;
}
};
});
从 Controller 调用现在应该可以工作了:
angular.module('newApp.newController', ['angularSpinner', 'ui.bootstrap']).controller('newController', function($q, $scope, utilityFactory, $http) {
return utilityFactory.getDevice().then(function(data) {
console.log(data);
}).catch(function(error) {
console.error(error);
});
});
关于javascript - 类型错误 : Cannot call method 'then' of undefined Angularjs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35737914/