Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angularjs/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 试图在401服务器响应上触发ui模式_Javascript_Angularjs - Fatal编程技术网

Javascript 试图在401服务器响应上触发ui模式

Javascript 试图在401服务器响应上触发ui模式,javascript,angularjs,Javascript,Angularjs,我试图在服务器响应401状态码时启动登录模式。根据这个指南,我创建了一个状态码拦截器,如下所示 // intercept http status codes app.config(function ($httpProvider) { $httpProvider.interceptors.push(['$injector', function ($injector) { return $injector.get('AuthInterceptor'); }]); })

我试图在服务器响应401状态码时启动登录模式。根据这个指南,我创建了一个状态码拦截器,如下所示

// intercept http status codes
app.config(function ($httpProvider) {
    $httpProvider.interceptors.push(['$injector', function ($injector) {
        return $injector.get('AuthInterceptor');
    }]);
});

app.factory('AuthInterceptor', function ($rootScope, $q) {
    return {
        responseError: function (res) {
            if (res.status === 401) {
                console.log('AuthInterceptor says you are not authorized');
            }
            if (res.status === 404) {
                console.log('AuthInterceptor says this page is not found');
            }
            return $q.reject(res);
        }
    };
});

当我尝试将$modal注入我的AuthInterceptor工厂时,我得到一个循环依赖项错误。从这样的内容触发$modal的好做法是什么?我链接的指南使用这个AuthInterceptor工厂来广播“Auth_事件”,这些事件只是常量字符串。除了广播这些auth_事件之外,它们没有显示出任何用途,所以我不明白它们是如何工作的。除了我的主要问题之外,有人能澄清这些身份验证事件的作用吗?

由于
$modal
服务依赖于
$http
,因此您得到了一个循环依赖性错误。这是依赖于
$http
自身的
$http
拦截器的常见问题。幸运的是,解决方法很简单:您需要将
$injector
注入拦截器,然后从注入器中检索
$model
,如下所示:

 app.factory('AuthInterceptor', function ($rootScope, $q, $injector) {
    return {
        responseError: function (res) {

            var $modal = $injector.get('$modal');

            if (res.status === 401) {
                //you can use $modal here...
                console.log('AuthInterceptor says you are not authorized');
            }
            if (res.status === 404) {
                console.log('AuthInterceptor says this page is not found');
            }
            return $q.reject(res);
        }
    };
});

谢谢你,这起了作用,让我对正在发生的循环依赖有了更好的理解。关于检查模态当前是否打开,您有什么建议吗?例如,涉及此http拦截器的示例。我有一个模式登录表单。多亏了你,我现在可以在拦截401状态码时打开此模式。当输入无效凭证时,登录表单本身将发送401状态代码,然后在原始凭证上堆叠新的登录模式。我该如何避免这种情况?