angularjs - AngularJS : how to reroute to another state after error handling

标签 angularjs error-handling state http-status-code-403 reroute

我想在我的Angular应用中制作一个或多或少的通用错误处理程序。

例如,我收到带有此链接的邮件:mysite/messages/151
单击此邮件:如果未登录,我的框架将返回403(故意)。

所以我创建了这个工厂。目前,它仅查找403错误,然后将用户路由到登录页面。

app.factory('httpRequestInterceptor', ['$q', '$location', '$rootScope', function($q, $location) {

    return {
        'responseError': function(rejection) {
            if (rejection.status === 403) {

                $location.path('/user/login');
                return $q.reject(rejection);
            }
        }
    };
}]);

在app.config中,我添加了以下行:
app.config(['$httpProvider', function($httpProvider)
{

    $httpProvider.interceptors.push('httpRequestInterceptor');

现在,当我收到403时,我将转到正确的路径:/user/login
到现在为止还挺好。

但是...我想以某种方式添加$ state,以便我知道调用的URL是什么(messages/151),以便我可以返回正确的位置并显示该消息。

我不能在工厂中使用$ state(由于一些我还不了解的技术东西而出错($ http vs $ state?),所以现在我很困惑如何完成这些工作。

所以,我想要:

1)在URL上的403错误进入登录状态(有效)

2)从用户(工作)获取登录凭据

3)登录成功后转到URL(不是一个线索)

也许我应该使用另一种方法,但是我无法解决这个问题。所以希望有人可以帮助我吗?

最佳答案

好的,这就是我想出的。谢谢!

/**
 * Error handling on httpRequests.
 *
 * generic: use rejection.status like: if (rejection.status === 403) {return     $q.reject(rejection);}
 * custom:  check fromState['current']['name'] for state name
 *
*/
app.factory('httpRequestInterceptor', ['$q', '$location', '$injector', '$timeout', '$stateParams', function($q, $location, $injector, $timeout, $stateParams) {

    return {
        'responseError': function(rejection) {
            var fromState = $injector.get('$state');

            $timeout(function() {
                switch (fromState['current']['name']) {
                    case 'root.messages':
                        $injector.get('$state').go('root.login', $stateParams,
                                {location: false});

                        break;
                }
            }, 2000);
            return $q.reject(rejection);
        }
    };
}]);

关于angularjs - AngularJS : how to reroute to another state after error handling,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25267780/

相关文章:

javascript - 对通用 ID 的 Angular 访问

sql - TSQL错误检查代码不起作用

error-handling - try/catch block 如何实现?

javascript - React,如何从 parent 那里访问 child 的状态?无需更新 parent 的状态

javascript - 在与对象 react 时在 child 之间共享状态

angularjs - 将现有的 angularjs 应用程序转换为 ionic 后无法滚动

html - AngularJS 从 ng-repeat 设置父级高度

sql - 如何检测哪个值发生错误?

javascript - 在 ReactJS 中传递 props 并且它们不会加载,同时收到目标容器错误?

javascript - 二进制流到 Uint8Array - JavaScript