简体   繁体   English

如何在angularjs应用程序中限制视图

[英]how to restrict view in angularjs application

I want to restrict user's to access /dashboard view and /add-item view or any other view in my angular js application. 我想限制用户访问我的angular js应用程序中的/ dashboard视图和/ add-item视图或任何其他视图。

this is my router 这是我的路由器

app.config(function($stateProvider, $urlRouterProvider){

        $urlRouterProvider.otherwise('login');

        $stateProvider.
            state('app.dashboard', {
                url: '/dashboard',
                templateUrl: appHelper.viewsPath('dashboard/views/dashboard'),
                controller: 'DashBoardController as DashBordCtrl',
     }).

            // Add Item
            state('app.add-item', {
                url: '/add-item',
                templateUrl: appHelper.viewsPath('item/views/add-item'),
                controller: 'ItemController as ItemCtrl',
            })
        });

After login I am storing the token in my local storage. 登录后,我将令牌存储在本地存储中。 I want user to not access any view if token is not present. 如果令牌不存在,我希望用户不访问任何视图。

this is my login controller 这是我的登录控制器

$scope.register = function(credentials){
       LoginService.post(credentials,function(success){
           $state.go('app.add-item');
          SessionService.set("token",success.accessToken);


             },function(error){
       FlashService.showError("Please Enter Valid Email Password");
        });
    }
    }

On 401 error i am redirecting to login page like this: 在401错误上,我正在重定向到登录页面,如下所示:

app.config(function ($httpProvider) {
   // $http.defaults.headers.common.Authorization = '';
     delete $httpProvider.defaults.headers.common['X-Requested-With'];

    $httpProvider.interceptors.push(function ($location, $q, SessionService, FlashService) {
        return {
            request: function (config) {
                 config.headers = config.headers || {};
                config.headers.Authorization = SessionService.get('token');
                return config;
            },
            responseError: function (response) {
                if (response.status === 401) {
                   SessionService.unset('token');
                    $location.path('/login');
                }
                return $q.reject(response);
            }
        };
    });
});

But if I type /add-item in url, my add-item page is opening and then it suddenly close,because server return 401 ,and login page appear.I don't want to open any view if user is not login. 但是,如果我在url中键入/ add-item,我的add-item页面正在打开,然后突然关闭,因为服务器返回401,并且出现了登录页面。如果用户未登录,我不想打开任何视图。

I am new in angularjs and i am confusing how to do this. 我是angularjs的新手,我对此感到困惑。 Please help. 请帮忙。

If token is not present,You can save the user's location to take him back to the same page after he has logged-in.You can review following code in app.js: 如果令牌不存在,您可以保存用户的位置,以便在用户登录后将其带回到同一页面。您可以在app.js中查看以下代码:

app.config(function($stateProvider, $urlRouterProvider){    

        $stateProvider.
            state('app.dashboard', {
                url: '/dashboard',
                templateUrl: appHelper.viewsPath('dashboard/views/dashboard'),
                controller: 'DashBoardController as DashBordCtrl',
     }).

            // Add Item
            state('app.add-item', {
                url: '/add-item',
                templateUrl: appHelper.viewsPath('item/views/add-item'),
                controller: 'ItemController as ItemCtrl',
            })
 $urlRouterProvider.otherwise('login');
        });

$urlRouterProvider.otherwise('login') replace with $urlRouterProvider.otherwise('app/dashboard') in app.config.if it is $urlRouterProvider.otherwise('login') ,you have a token ,throw login page still. $ urlRouterProvider.otherwise('login')替换为app.config中的$ urlRouterProvider.otherwise('app / dashboard')。如果它是$ urlRouterProvider.otherwise('login'),则您仍然有一个令牌,仍然会出现登录页面。

 app.config(function ($httpProvider) {
       // $http.defaults.headers.common.Authorization = '';
         delete $httpProvider.defaults.headers.common['X-Requested-With'];

        $httpProvider.interceptors.push(function ($location, $q, SessionService, FlashService) {
            return {
                request: function (config) {
                     config.headers = config.headers || {};
                    config.headers.Authorization = SessionService.get('token');
                    return config;
                },
                responseError: function (response) {
                    if (response.status === 401) {
                       SessionService.unset('token');
                        $location.path('/login');
                    }
                    return $q.reject(response);
                }
     if (!SessionService.get('token');) {
                    /* You can save the user's location to take him back to                 the same page after he has logged-in */
                    $rootScope.savedLocation = $location.url();

                    $location.path('/login');
                }
            };
        });
    });

You should use resolve in your route configuration. 您应该在路由配置中使用resolve Example: 例:

state('app.add-item', {
            url: '/add-item',
            templateUrl: appHelper.viewsPath('item/views/add-item'),
            controller: 'ItemController as ItemCtrl',
            resolve: ['SomeService', function(SomeService) {
                return SomeService.getDataFromApi();
            }]
        })

Looking at this example, if SomeService returns 401, meaning an error, that route controller will never instantiate and therefor you cannot access the view. 查看此示例,如果SomeService返回401(表示错误),则该路由控制器将永远不会实例化,因此您无法访问视图。 Your interceptor will still do his job, and redirect to login when 401 happens, but now it will happen smoothly and with no flash of the view. 您的拦截器仍会执行其工作,并在401发生时重定向到登录名,但是现在它将顺利进行并且视图没有闪烁。

This is a good way to do, and it will solve that problem of yours and also some others you might encounter later. 这是一个很好的方法,它将解决您以及以后可能遇到的其他问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM