简体   繁体   English

如何在完成不同文件的代码后才能执行某些代码?

[英]How to execute some code only after code from a different file has finished?

I'm using AngularJS and I have a controller where I handle the authentication of the user. 我正在使用AngularJS,我有一个控制器,我处理用户的身份验证。 Then I have several different controllers that make API calls. 然后我有几个不同的控制器进行API调用。 Those API calls need to be executed AFTER the authentication code has finished. 这些API调用需要在身份验证代码完成后执行。

The problem is that since I load my controllers in parallel like the following, I don't even know which file will load and execute first: 问题是,由于我像以下一样并行加载我的控制器,我甚至不知道哪个文件将首先加载和执行:

<script type="text/javascript" src="./app/controllers/authController.js"></script>
<script type="text/javascript" src="./app/controllers/softwareController.js"></script>

I think this means that the flag or promise (to know when authentication has finished) needs to be declared BEFORE including those files, as a global flag. 我认为这意味着需要在包含这些文件之前声明标志或承诺(知道何时完成身份验证)作为全局标志。

But I can't declare the promise outside&before the files because I wouldn't be able to pass the resolve function to it (because the authentication function wouldn't even be declared yet). 但我无法在文件之外和文件之前声明承诺,因为我无法将resolve函数传递给它(因为验证函数甚至还没有声明)。

What's the best way to go about this? 最好的方法是什么?

Make a service for authentication and inject it into your controllers. 为身份验证提供服务并将其注入您的控制器。 In your service, add a function for authentication with a success callback. 在您的服务中,使用成功回调添加用于身份验证的功能。 Inject this service into your controllers. 将此服务注入您的控制器。 In your controllers you can execute your login inside the success callback function. 在控制器中,您可以在成功回调函数中执行登录。

Service 服务

angular.module('app', []).service('authService', function(){
   this.authenticate = function(successCallback) {
      // Perform authentication here
      successCallback();
   }
});

Controller 调节器

angular.module('app').controller('firstCtrl', function($scope, authService){
   authService.authenticate(function onSuccess(){
      // Authentication was successful
   });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM