How can I send request again in response interceptor?

前端 未结 4 1955
花落未央
花落未央 2021-01-30 21:59

I\'ve made an interceptor in my application that detects session loss (server sends an HTTP 419). In this case, I need to request a new session from the server, and then I would

4条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-30 22:30

    Here is my solution using promises for those interested. Basically you need to request a new session, and wait for the response before sending a new request corresponding to the original request (using response.config). By returning the promise $http(response.config) you ensure that the response will be treated as if it was the original request.
    (syntax may not be the best as I'm new to promises)

    angular.module('myapp', [ 'ngResource' ]).factory(
        'MyInterceptor', 
        function ($q, $rootScope) {
            return function (promise) {
                return promise.then(function (response) {
                    // do something on success
                    return response;
                }, function (response) {
                    if(response.status == 419){
                        // session lost
                        var Session = $injector.get('Session');
                        var $http = $injector.get('$http');
                        // first create new session server-side
                        var defer = $q.defer();
                        var promiseSession = defer.promise; 
                        Session.query({},function(){
                            defer.resolve();
                        }, function(){
                           // error
                           defer.reject();
                        });       
                        // and chain request
                        var promiseUpdate = promiseSession.then(function(){
                            return $http(response.config);
                        });
                        return promiseUpdate;
                    }
                    return $q.reject(response);
                });
            };
        }).config(function ($httpProvider) {
            $httpProvider.responseInterceptors.push('MyInterceptor');
        });
    

提交回复
热议问题