[英]How to execute some code only after code from a different file has finished?
我正在使用AngularJS,我有一个控制器,我处理用户的身份验证。 然后我有几个不同的控制器进行API调用。 这些API调用需要在身份验证代码完成后执行。
问题是,由于我像以下一样并行加载我的控制器,我甚至不知道哪个文件将首先加载和执行:
<script type="text/javascript" src="./app/controllers/authController.js"></script>
<script type="text/javascript" src="./app/controllers/softwareController.js"></script>
我认为这意味着需要在包含这些文件之前声明标志或承诺(知道何时完成身份验证)作为全局标志。
但我无法在文件之外和文件之前声明承诺,因为我无法将resolve函数传递给它(因为验证函数甚至还没有声明)。
最好的方法是什么?
为身份验证提供服务并将其注入您的控制器。 在您的服务中,使用成功回调添加用于身份验证的功能。 将此服务注入您的控制器。 在控制器中,您可以在成功回调函数中执行登录。
服务
angular.module('app', []).service('authService', function(){
this.authenticate = function(successCallback) {
// Perform authentication here
successCallback();
}
});
调节器
angular.module('app').controller('firstCtrl', function($scope, authService){
authService.authenticate(function onSuccess(){
// Authentication was successful
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.