D
D
Dmitry Arushanov2015-12-14 15:35:14
JavaScript
Dmitry Arushanov, 2015-12-14 15:35:14

Restangular, How to retry a request in case of an error?

Good day to all. I use here Restangular in the project. And I make a request to the API server. In each request, an access token is passed. And if it is outdated, you need to refresh it, and then, in theory, repeat the request. I found such an example in the documentation,
https://github.com/mgonto/restangular#seterrorinte...
and implemented it like this according to my logic

Restangular.setErrorInterceptor(
          function (response, deferred, responseHandler) {
            if (response.status == 403) {
              //refresh token
              AuthService.refreshAccessToken().then(
                function (res) {
                 //update new accessotken and refresh in local storage
                  Session.create(res);
                  
                   //this line is not in example, but as i understand i need update token in headers
                  response.config.headers['X-ACCESS-TOKEN'] = res.data.token;
                 //this line the same as in example 
                 $http(response.config).then(responseHandler, deferred.reject);
                }, function (response) {
                  Session.destroy();
                  return false;
                }
              );
              return false;
            }
            return true;
          }
        );

But looking through the requests through the developer console, I see that the repeated request goes away, but the data is not returned anywhere ... I mean in the controller function, from where the request was originally made. Maybe I missed something?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
N
Nicholas, 2015-12-14
@daruwanov

I think you need to manually resolve your external promise:

$http(response.config).then(function(data) {
    deffered.resolve(data);
 }, deferred.reject);

But I'm honestly not sure.

S
Sergey, 2015-12-14
Protko @Fesor

https://github.com/witoldsz/angular-http-auth - what you need is implemented here through a chain of promises, see how it's done, it's very convenient there. Or maybe just use this solution.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question