AngularJS在module.config中更改URL

时间:2014-01-30 00:54:49

标签: angularjs restangular angular-routing

我在angularjs App&中使用Restangular使用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 个答案:

答案 0 :(得分:15)

处理此问题的正确方法是在angular {{1>} run方法中配置restangular

app.run(Restangular , $location){
    Restangular.setErrorInterceptor(function (resp) {
        $location.path('/login');
        return false;
    });
}

答案 1 :(得分:4)

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

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

另请查看我的其他答案:

答案 2 :(得分: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);

}]);

这种类似的东西在你的情况下是否有用吗?

答案 3 :(得分:1)

如果我理解正确,您希望根据服务器返回给您的状态代码将用户重定向到登录页面?像404或403?

如果是这种情况,我就可以在我的某个应用中使用setErrorInterceptor处理404和403上的重定向。这可能不是最好的方法,但到目前为止我的工作一直很好。

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