【问题标题】:AngularJS change URL in module.configAngularJS 在 module.config 中更改 URL
【发布时间】:2014-02-03 06:46:03
【问题描述】:

我在我的 angularjs 应用程序中使用 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;
        });
    });

【问题讨论】:

  • 您期待什么样的错误? 404、500、找不到资源?这些有 ng 路由事件。 docs.angularjs.org/api/ngRoute.$route$routeChangeError。然后通常我可以访问 $location 并使用 $location.path('YOUR PATH');
  • 所有 4xx 和 5xx 错误。 @Matthew.Lothian 我想在一个地方处理错误,restangular 为我提供了此功能,但问题在于更改 .config() 方法中的路径
  • 我对 Restangular 不熟悉,但一般来说,我可能不是要走的路。我将举例说明我之前是如何设置的。

标签: angularjs restangular angular-routing


【解决方案1】:

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

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

【讨论】:

  • 谢谢。给其他观众答案的小提示。您可以使用$state.go(...) 代替$location.path(...)。无论如何,您都在运行块中。
【解决方案2】:

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

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

同时查看我的其他答案:

【讨论】:

  • tnx 为您的解决方案,但它会引发此错误:错误:[$injector:unpr] 未知提供者:$location
【解决方案3】:

这里的想法是更具体地说明如何请求资源。在这个项目摘录中,我使用routeProvider.whenresolve 选项根据路径输入查找资源,并在解析路由之前将结果注入为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 的情况下,这样的东西有用吗?

【讨论】:

  • tnx 你。但我使用 Restangular 是因为它的强大功能使我能够过滤响应和请求。
【解决方案4】:

如果我理解正确,您想根据服务器返回给您的状态代码将用户重定向到登录页面吗?像 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;
    });
}]);

【讨论】:

  • tnx 为您的解决方案。你使用纯javascript代码来处理这个问题
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-10-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多