在拦截器中重试Restangular调用

Tho*_*ock 6 angularjs restangular

官方的restangular文档提供此代码示例以在ErrorInterceptor中重试请求:

var refreshAccesstoken = function() {
    var deferred = $q.defer();

    // Refresh access-token logic

    return deferred.promise;
};

Restangular.setErrorInterceptor(function(response, deferred, responseHandler) {
    if(response.status === 403) {
        refreshAccesstoken().then(function() {
            // Repeat the request and then call the handlers the usual way.
            $http(response.config).then(responseHandler, deferred.reject);
            // Be aware that no request interceptors are called this way.
        });

        return false; // error handled
    }

    return true; // error not handled
});
Run Code Online (Sandbox Code Playgroud)

但是,正如它在评论中所说,第二次尝试不会触发任何拦截器,因为它直接使用$ http.

有没有办法让第二个请求也通过Restangular管道并执行ErrorInterceptor?

Bal*_*zar 4

实际上,使用Restangular提出的请求承诺被设计为仅解决一次。如果被拒绝,您无法重新发送。

我真的不知道你是否想要一个可重用的errorInterceptor,但该服务的工作方式似乎不允许简单response object config.

您可以做的一件事是保存对对象的引用,然后在拦截器中使用它。

你应该有你的理由,但我必须警告你这一点,因为如果失败并且它持续存在,你可能会得到无限的调用,因为 Restangular总是会调用errorInterceptor.

我为演示做了一些Plunkr模拟,只需打开网络选项卡并单击按钮,您应该会看到所有请求都通过那里。