Restangular拦截器来处理$ q.all请求

时间:2017-12-04 03:12:01

标签: angularjs interceptor restangular angular-http-interceptors

我需要Restangular拦截器的帮助。我可以重试请求所有失败的API调用,但数据没有返回到调用函数的success方法。

当不使用$q.all时,拦截器工作正常。我需要帮助如何返回数据。

以下是我的拦截器代码:

authrestangular.factory("AuthRestangular", function (Restangular, $q, $injector, $location, localStorageService, $filter, $timeout, cfpLoadingBar, $cookies) {
    return Restangular.withConfig(function(RestangularConfigurer) {
        RestangularConfigurer.addFullRequestInterceptor(function (element, operation, route, url, headers) {
            cfpLoadingBar.start();
            var token = $cookies.get('token');
            if (token) {
                headers.Authorization = "Bearer " + token;
            }
        });

        RestangularConfigurer.setErrorInterceptor(function (response, deferred, responseHandler) {
            if (response.status === 401) {
                var prevConfig = response.config;
                _responseError($q, $injector, $location, response, prevConfig).then(function (res) {
                    console.log(res);
                    if (pendingRequests.length > 0) {
                        angular.forEach(pendingRequests, function (req) {
                            req.headers.Authorization = 'Bearer ' + res.access_token;
                            _retryHttpRequest(res, req, deferred);
                        });
                        pendingRequests = [];
                    } else {
                        _retryHttpRequest(res, response.config, deferred)
                    }
                    var authService = $injector.get("authService");
                    authService.authentication.isRefreshing = false;
                }, function (err) {
                    console.log("Error", err);
                });
                return false;
            }

            if (response.status === 500) {
                $location.path("error");
            }

            return true;
        });

        RestangularConfigurer.addResponseInterceptor(function (data, operation, what, url, response, deferred) {
            var extractedData;

            if (operation === "getList") {
                extractedData = response.data.Rows;
                extractedData.pagination = response.data.Pagination;
            } else {
                extractedData = response.data;
            }

            return extractedData;
        });

    });
});

var _responseError = function ($q, $injector, $location, response, prevConfig) {
    var deferred = $q.defer();
    var authService = $injector.get("authService");
    if (authService.authentication.isRefreshing) {
        pendingRequests.push(prevConfig);
    } else {
        authService.refreshToken().then(function (response) {
            if (pendingRequests.length > 0) {
                angular.forEach(pendingRequests, function (req) {
                    req.headers.Authorization = 'Bearer ' + response.access_token;
                    _retryHttpRequest($injector, req, deferred)
                });
            } else {
                prevConfig.headers.Authorization = 'Bearer ' + response.access_token;
                _retryHttpRequest($injector, prevConfig, deferred);
            }
            deferred.resolve(response);
        }, function () {
            authService.logOut();
            $location.path("/portal");
            deferred.reject(response);
        });
    }
    authService.authentication.isRefreshing = true;
    return deferred.promise;
}

var _retryHttpRequest = function ($injector, config, deferred) {
    $http = $http || $injector.get("$http");
    $http(config).then(function (response) {
        var extractedData;

        if (response.data.Rows && response.data.Pagination) {
            extractedData = response.data.Rows;
            extractedData.pagination = response.data.Pagination;
        }
        else {
            extractedData = response.data;
        }

        deferred.resolve(extractedData);
    }, function (response) {
        deferred.reject(response);
    });
}

上面是我的拦截器的所有代码,refreshToken()只是刷新我的令牌。我在这里做的是,如果调用了refreshToken()函数,那么我设置一个标志,我的令牌仍在刷新。这将解决令牌刷新时的问题,而其他API调用仍在使用旧的访问令牌。

以下是调用api的函数

var initializeDDLs = function () {
    var ddlAPIcalls = [
        authRestangular.one("PositionAPI/getddl").get(),
        authRestangular.one("Employee201API/getddl").get(),
        authRestangular.one("StatusAPI/getddl").get({ moduleId: Common.constants.civilStatus }),
        authRestangular.one("TypeAPI/getddl").get({ moduleId: Common.constants.bloodType }),
        authRestangular.one("PositionAPI/getPositionCodeddl").get(),
        authRestangular.one("TypeAPI/getddl").get({ moduleId: Common.constants.educationalLevel }),
        authRestangular.one("EmployerAPI/getddl").get(),
        authRestangular.one("BusinessUnitAPI/getddl").get(),
        authRestangular.one("TypeAPI/getddl").get({ moduleId: Common.constants.locationType }),
        authRestangular.one("StatusAPI/getddl").get({ moduleId: Common.constants.employmentStatus }),
        authRestangular.one("StatusAPI/getddl").get({ moduleId: Common.constants.employmentStatusBefore }),
        authRestangular.one("TypeAPI/getddl").get({ moduleId: Common.constants.salaryType }),
        authRestangular.one("TypeAPI/getddl").get({ moduleId: Common.constants.basicRateType }),
        authRestangular.one("TypeAPI/getddl").get({ moduleId: Common.constants.documentType }),
        authRestangular.one("Employee201API/getsystemroleddl").get(),
        authRestangular.one("ShiftAPI/getddl").get(),
        authRestangular.one("KeyQuestionAPI/getddl").get()
    ];

    $q.all(ddlAPIcalls)
        .then(function (response) {
            console.log(response);
        }, function (err) {
            console.log(response);
        });

};

代码不会触发.then响应,这是成功响应,假设将返回即将显示的数据。

请帮忙。不知道该怎么办。

1 个答案:

答案 0 :(得分:0)

在将API推送到列表之前,您应该检查条件。 例如:

var apiList = [];

if (!$rootScope.apiOneData) {
  apiList.push(ApiOne.then(
    function (data) {
      // Success this API
      $rootScope.apiOneData = data;
    },
    function (error) {
      // Handle error in this API
    }
  ));
}

if (!$rootScope.apiTwoData) {
  apiList.push(ApiTwo.then(function (data) {
    // Success this API
    $rootScope.apiOneData = data;
  }));
}

if (!apiList.length) {
  return;
}

$rootScope.isLoading = true;

return $q.all(apiList)
  .then(function (data) {

    // Success all
    // Do something
  }, function (error) {
    // Error
    // Do something
  });