angularjs redirect to login page if not authenticated with exceptions

后端 未结 2 676
攒了一身酷
攒了一身酷 2020-12-18 14:34

EDIT: forgot to mention that i\'ve been working with AngularJs for a week only, so if you see something you think should be changed for the better and is not related to the

2条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-18 14:56

    An error service like this could help to handle what to do according to status in responses:

    'use strict';

    /**
     * Error Service
     */
    
    angular.module('app.errorService', [])
            .factory("errorService", function ($route, $location) {        
                    return {   
                        checkAndReturnError: function(a,b,c) {
                            if (a.status === 401){
                                (function(){
                                    return $location.path("/accounts/login");
                                }());
                                return;
                            }
                            if (a.status === 404)
                                return;
    
                               alert("Error \n *" + a.data.message);
    
                        }
                    };
            });
    

    Then when you do your calls if the response status is 401 it will redirect. The vbad thing agout this is you have to add it to all calls:

                $scope.pageChanged = function() {
                    $scope.Promise = Resource.get({}, function(response) {
                    }, errorService.checkAndReturnError);
                };
    

提交回复
热议问题