angular.js - How to configure the http interceptor in angularjs to resend the request when encountering a 404 response
PHP中文网
PHP中文网 2017-05-15 17:02:16
0
1
507

Currently I can only jump to the error page when the request returns 404

    //    创建拦截器
    app.factory('Http404Interceptor', function ($q)
    {
        return {
            responseError: function (response)
            {
                if(response.status == 404){
                    location.href = appURL.fullUrl + 'error';
                }
                return $q.reject(response);
            }
        }
    });
    
    //    配置拦截器给app
    app.config(function ($httpProvider)
    {
        $httpProvider.interceptors.push('Http404Interceptor');
    });

But the current requirement is to re-initiate the request to another link (such as: a.php) when the request returns 404. How should I write it so that the interceptor can realize this function?

PHP中文网
PHP中文网

认证高级PHP讲师

reply all(1)
漂亮男人

Correction:

What does "request another link (such as: a.php)" mean? Request another api获取数据作为fallback?

If that’s what it means, isn’t it quite simple:

//    创建拦截器
//之前忘了这里还有个循环依赖的问题,我去
app.factory('Http404Interceptor', function ($q, $injector)
{
    return {
        responseError: function (response)
        {
            if(response.status == 404){
                var $http = $injector.get('$http');
                return $http.get('anotherUrl');
            }
            return $q.reject(response);
        }
    }
});
    
//    配置拦截器给app
app.config(function ($httpProvider)
{
    $httpProvider.interceptors.push('Http404Interceptor');
});
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template