简体   繁体   中英

AngularJs 1.5.8: how to check if the token is valid before sending every $http (get/post) request

I am new to Angularjs and wondering how to check the token 's expire date and time before sending any request.

I googled and found there are concepts like interceptors and decorators in angular but I am a bit confused which one to use and how. Or is there any better way to do it.

What am I doing right now?

I have created a service that has GET, POST functions take url, data and config as parameters and there I am checking the token. I know this is not the right approach.

You can use an interceptor that will configure every $http call. enter link description here

You can write interceptor which will cancel invalid token request before it is actually sent:

return {
      'request': function(config) {
        if (condition) {
          var canceler = $q.defer();
          config.timeout = canceler.promise;
          canceler.resolve();
        }
        return config;
      }
}

Obviously, you can manipulate config before returning it and (for example) change token.

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