【问题标题】:AngularJs http request priorities and http interceptorsAngularJs http请求优先级和http拦截器
【发布时间】:2019-06-18 18:46:36
【问题描述】:

我一直在查看我不久前制作的一个应用程序,并且有一个特定页面,其中最后加载了详细信息。因此,它似乎正在排队请求(在它之前有超过 6 个其他请求),这导致页面变慢。

我想我可以找到一个解决方案来优先处理这些请求,我发现了这个:

How to prioritize requests in angular $http service?

所以我创建了它的版本并将其添加到我的拦截器中:

// Add our auth interceptor to handle authenticated requests
$httpProvider.interceptors.push('authInterceptor');
$httpProvider.interceptors.push('httpPriorityInterceptor');

拦截器如下所示:

function factory($injector, $q) {
    var requestStack = [], // request stack
        $http = null; // http service to be lazy loaded

    return {
        request: request,
        responseError: responseError
    };

    //////////////////////////////////////////////////

    function request(config) {
        // Lazy load $http service
        if (!$http) {
            $http = $injector.get('$http');
        }

        if (!config.hasBeenRequested) {
            config.hasBeenRequested = true;
            config.priority = config.priority || 3;

            console.log(config);

            // add a copy of the configuration
            // to prevent it from copying the timeout property
            requestStack.push(angular.copy(config));

            // sort each configuration by priority
            requestStack = requestStack.sort(sort);

            // cancel request by adding a resolved promise
            config.timeout = $q.when();
        }

        // return config
        return config;
    }

    function responseError(rejection) {
        // check if there are requests to be processed
        if (requestStack.length > 0) {
            requestStack.reduceRight(function(promise, config) {
                return promise.finally(function() {
                    return $http(config);
                });
            }, $q.when());

            requestStack.length = 0;
        }

        // return rejected request
        return $q.reject(rejection);
    }

    //////////////////////////////////////////////////

    function sort(config1, config2) {
        return config1.priority < config2.priority;
    }
}

问题是,它似乎也在拦截模板请求。我对此没有问题,但他们没有解决。相反,我得到了很多错误:

错误:[$templateRequest:tpload] 无法加载模板:app/accounts/accounts.html(HTTP 状态:-1)

有没有人遇到过这种情况?有什么办法可以解决这个问题吗?

【问题讨论】:

    标签: angularjs http


    【解决方案1】:

    您应该知道每个请求,例如 html 文件、css 文件和 ... 都会进入拦截器。 在您的情况下,您不需要优先考虑这些文件。因此您可以过滤您的请求,例如:

    if (config.url.toString().toLowerCase().includes("api")) {
        //place your functionality
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-19
      • 2016-10-05
      • 2014-05-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多