Search code examples
javascriptangularjsinterceptorangular-resourceangular-services

Recall $resource factory within interception


I have the following factory:

.factory('Request', ['$resource', 'general',
        function ($resource) {
            return $resource(baseURL + ':resourceName/', {}, {
                get : {
                    method : 'GET',
                    isArray : true,
                    transformResponse : function (data, headers) {
                        return JSON.parse(data).data;
                    },
                    interceptor: {
                        responseError : function (data) {
                            gnrl.logIn({},false,function(){console.log("test");});
                            // ???? How to recall this request? 
                        }
                    }
                }
            });
        }
    ]);

What I'm trying to do is, if the user has some trouble in this request, the user should login again and the request should be executed again.

The request factory is called as follows:

Request.get(params, headers, function (res) {
    //does some operation with results  
});

I have seen some related questions but none of them could fit my situation completely.


Solution

  • It is solved using the answers referred in the question. As said, the main idea was using $promise instead of interceptor.

    I have solved the problem as follows:

    The following is a function in my service

    self.doRequest = function(nOfRetries, params, successFunction) {
            function fai(a) {
                nOfRetries--;
                self.logIn(function(){self.doRequest(nOfRetries);});
            }
            if (nOfRetries >= 0) {
                Request.get(params).then(successFunction).catch(fai);
            }
        }
    

    Login is just another function in the same service and as a callback function i send a request to this function.

    doRequest is called as follows:

    general.doRequest(3, params/*parameters used in request*/, function (res) {
                /***cb function for your initially request*/
    });
    

    As last, you see the Request factory:

    .factory('Request', ['$resource',
            function ($resource) {
                var res = $resource(baseURL + ':resourceName/', {}, {
                        get : {
                            method : 'GET'
                        }
                    });
                return {
                    get : function (arguments) {
                        return res.get(arguments).$promise;
                    }
                };
            }
        ])
    

    Note that any error (server-side or not) occurred in doRequest's success callback function will also lead to executing failure callback function.