正如其他一些答案中提到的,您需要从utils.getData
函数中返回Promise
。 Angular的$q
助手可以让你做到这一点。但是,其他一些答案显示您这样做的方式违背了最佳做法。当使用$q
,最好的做法是要做到以下几点:
var myPromise = $q(function (resolve, reject) {
// Do some logic in here that is asynchronous and either invoke resolve with
// the results or reject with an error that may have occurred
});
因此,你的代码就变成了:
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 */
return $q(function (resolve, reject) {
if (!window.plugin) {
// You can handle this case as a rejection of the promise
reject(new Error('Window plugin not found'));
return;
}
var launcher = getLauncher();
console.log("Fetching data from device");
//Cordova js is returning this method
// When device is ready it will "resolve" the promise and
// invoke any of the ".then()" functions you add to the promise
// If an error occurs, it will invoke any ".catch()" functions
// that you have added.
launcher.getDevice(resolve, reject);
});
};
return utils;
})
有关$q
服务的更多信息,请从官方AngularJS文档,检查这个职位: https://docs.angularjs.org/api/ng/service/ $ q
此外,如果您想了解更多关于承诺和JavaScript中的异步编程的一些资源:
的承诺整洁的可视化工具 - http://bevacqua.github.io/promisees/#
教程上的承诺 - https://www.toptal.com/javascript/javascript-promises
另一件事是寻找到作为AngularJS最佳实践的一般指导是角风格导游约翰爸爸:https://github.com/johnpapa/angular-styleguide
最后,你有你的模块设置的方式稍微关闭。每次调用angular.module(moduleName, dependencies)
将创建一个具有这些依赖关系的新模块。虽然将角度应用分解为多个模块是一个好主意,但您需要确保使用ng-app
指令引用的根或“主”应用具有对所有子模块的引用,并且任何引用依赖关系的模块从另一个模块中将该模块包含在其依赖列表中。
在你的情况,你创建一个名为newApp.newController
模块,但你拥有它,因为它试图引用utilityFactory
,这是在所谓的newApp.utility
一个单独的模块定义的,但不是由你newApp.newController
模块引用它不会工作。为了解决这个问题,请执行下列操作:
angular.module('newApp.newController', ['angularSpinner', 'ui.bootstrap', 'newApp.utility'])
// Make sure to add 'newApp.utility' to the dependencies of the 'newApp.newController' module.
或者,你可以创建两个控制器和同一模块中的效用工厂:绕角模块系统
// Create the module once
angular.module('newApp', ['angularSpinner', 'ui.bootstrap']);
// Reference it by invoking it with just one parameter
angular.module('newApp').controller('newController', ...);
angular.module('newApp').factory('utilityFactory', ...);
用法和最佳实践能在这里找到: https://github.com/johnpapa/angular-styleguide/blob/master/a1/README.md#modules
'getData'不返回任何东西 –
我用这个也 回报launcher.getD设备(成功,失败); – Bharath
但是它不会为'else'返回任何东西,而'launcher.getDevice'返回什么? – charlietfl