3

Restangular在我的 angularjs 应用程序中使用setErrorInterceptor并用于在一个地方处理响应错误。如果发生错误,我想将用户重定向到登录页面。我知道唯一的providers&constants在配置阶段是可注入的。

var app = angular.module('ourstandApp', ['ngRoute', 'restangular', 'ui.bootstrap', 'ngCookies', 'angularFileUpload']);
    // Global configuration

    app.config(function (RestangularProvider, baseRequestConfig, $routeProvider, urlsProvider) {
        var getBaseRequestUrl = function () {
            return baseRequestConfig.protocol + "://" + baseRequestConfig.hostName + ":" + baseRequestConfig.portNumber + baseRequestConfig.resourcePath;
    }
        var initializeRoute = function () {
            $routeProvider.when('/', {
                controller: LoginController,
                templateUrl: 'views/login.html'
            }).
            otherwise({
                redirectTo: '/'
            });
        }

        initializeRoute();
        RestangularProvider.setBaseUrl(getBaseRequestUrl());
        RestangularProvider.setErrorInterceptor(function (resp) {
            goToLogin();  //  i want to change url to login page
            return false;
        });
    });
4

4 回答 4

15

处理这个问题的正确方法是在 angularjs 的run方法中配置 restangular

app.run(Restangular , $location){
    Restangular.setErrorInterceptor(function (resp) {
        $location.path('/login');
        return false;
    });
}
于 2014-02-02T22:46:03.307 回答
4

注入$injector配置块并在需要时邀请$location

RestangularProvider.setErrorInterceptor(function (resp) {
   var $location = $injector.get('$location');
   $location.path('/login');
   return false;
});

另请查看我的其他答案:

于 2014-01-30T02:02:15.913 回答
1

If I understand you correctly you want to redirect the user to a login page based on a status code returned to you by the server? Like a 404 or 403?

If that's the case this is how I handle redirects on a 404 and 403 using setErrorInterceptor in one of my apps. This may not be the best way to do this, but It's been working just fine so far for me.

app.config(['RestangularProvider', function (RestangularProvider) {
    RestangularProvider.setErrorInterceptor(function (response) {
        // Redirect the user to the login page if they are not logged in.
        if (response.status == '403' && response.data.detail == 'Authentication credentials were not provided.') {
            var next = window.location.pathname + window.location.hash;

            window.location.href = '/accounts/login/?next=' + next;
        }

        // Redirect the user on a 404.
        if (response.status == '404') {
            // Redirect to a 404 page.
            window.location.href = '/#/';
        }

        return response;
    });
}]);
于 2014-01-30T23:07:58.180 回答
1

这里的想法是更具体地说明如何请求资源。在这个项目的摘录中,我使用的resolve选项是routeProvider.when根据路径输入查找资源并像ArticleRequest解析路径之前一样注入结果。

如果 api 调用路由失败并$routeChangeError触发事件

App.config(['$routeProvider', '$locationProvider', 'TEMPLATE_PATH',
function ($routeProvider, $locationProvider, TEMPLATE_PATH) {

    $routeProvider.
    when('/', {
        templateUrl: TEMPLATE_PATH + 'views/Home.html',
        controller: 'HomeCtrl',
        caseInsensitiveMatch: true
    }).
    when('/:slug/:nocache?', {
        templateUrl: TEMPLATE_PATH + 'views/Article.html',
        controller: 'ArticleCtrl',
        caseInsensitiveMatch: true,
        resolve: {
            ArticleRequest: ['$http', '$route', function ($http, $route) {
                return $http.post('/api/article/GetArticleBySlug',
                    {
                        slug: $route.current.params.slug,
                        nocache: !!$route.current.params.nocache && $route.current.params.nocache == 'preview'
                    });
            }]
        }
    }).
    otherwise({
        redirectTo: '/'
    });

    // configure html5 to get links working on jsfiddle
    $locationProvider.html5Mode(true);   

}]);

这是$routeChangeError处理程序的一个非常简单的实现

App.run(['$rootScope', '$location', function($rootScope, $location) {

    $rootScope.$on('$routeChangeError', function (e, current, previous, rejection) {

        console.log("ROUTE ERROR:", current, previous, rejection);
        // you might redirect here based on some logic
        $location.path('[YOUR PATH]');

    });

}]);

这是控制器

ViewControllers.controller('ArticleCtrl', 
['$scope', '$http', '$routeParams', 'ArticleRequest',
function ($scope, $http, $routeParams, ArticleRequest) {

    console.log(ArticleRequest);

}]);

对于Restangular,这样的东西对你有用吗?

于 2014-01-30T01:16:02.157 回答