简体   繁体   中英

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. Then I have several different controllers that make API calls. Those API calls need to be executed AFTER the authentication code has finished.

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).

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
   });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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