search

Home  >  Q&A  >  body text

angular.js - How to configure the http interceptor in angularjs to resend the request when encountering a 404 response

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中文网2787 days ago518

reply all(1)I'll reply

  • 漂亮男人

    漂亮男人2017-05-15 17:04:16

    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');
    });

    reply
    0
  • Cancelreply