本文實例講述了AngularJS實現(xiàn)用戶登錄狀態(tài)判斷的方法。分享給大家供大家參考,具體如下:
使用AngularJS的單頁面應(yīng)用時,由于是本地路由在控制頁面跳轉(zhuǎn),但是有的時候我們需要判斷用戶是否登錄來判斷用戶是否能進(jìn)入界面。
angularjs是mvc架構(gòu)所以實現(xiàn)起來很容易也很靈活,我們只MainController里增加一個路由事件偵聽并判斷,這樣就可以避免未登錄用戶直接輸入路由地址來跳轉(zhuǎn)到登錄界面地址了
代碼中的 $rootScope.user是登錄后把用戶信息放到了全局rootScope上,方便其他地方使用,$rootScope.defaultPage也是默認(rèn)主頁面,初始化的時候?qū)懰赖絩ootScope里的。
$rootScope.$on('$stateChangeStart',function(event, toState, toParams, fromState, fromParams){ if(toState.name=='login')return;// 如果是進(jìn)入登錄界面則允許 // 如果用戶不存在 if(!$rootScope.user || !$rootScope.user.token){ event.preventDefault();// 取消默認(rèn)跳轉(zhuǎn)行為 $state.go("login",{from:fromState.name,w:'notLogin'});//跳轉(zhuǎn)到登錄界面 }});
另外還有用戶已經(jīng)登錄,但是登錄超時了,還有就是增加后臺接口的判斷來增強(qiáng)安全性。不能完全依靠本地邏輯
我們在model里面增加一個用戶攔截器,在rensponseError中判斷錯誤碼,拋出事件讓Contoller或view來處理
app.factory('UserInterceptor', ["$q","$rootScope",function ($q,$rootScope) { return { request:function(config){ config.headers["TOKEN"] = $rootScope.user.token; return config; }, responseError: function (response) { var data = response.data; // 判斷錯誤碼,如果是未登錄 if(data["errorCode"] == "500999"){ // 清空用戶本地token存儲的信息,如果 $rootScope.user = {token:""}; // 全局事件,方便其他view獲取該事件,并給以相應(yīng)的提示或處理 $rootScope.$emit("userIntercepted","notLogin",response); } // 如果是登錄超時 if(data["errorCode"] == "500998"){ $rootScope.$emit("userIntercepted","sessionOut",response); } return $q.reject(response); } };}]);
別忘了要注冊攔截器到angularjs的config中哦
app.config(function ($httpProvider) { $httpProvider.interceptors.push('UserInterceptor');});
最后在controller中處理錯誤事件
$rootScope.$on('userIntercepted',function(errorType){ // 跳轉(zhuǎn)到登錄界面,這里我記錄了一個from,這樣可以在登錄后自動跳轉(zhuǎn)到未登錄之前的那個界面 $state.go("login",{from:$state.current.name,w:errorType});});
最后還可以在loginController中做更多的細(xì)節(jié)處理
// 如果用戶已經(jīng)登錄了,則立即跳轉(zhuǎn)到一個默認(rèn)主頁上去,無需再登錄if($rootScope.user.token){ $state.go($rootScope.defaultPage); return;}
另外在登錄成功回調(diào)后還可以跳轉(zhuǎn)到上一次界面,也就是上面記錄的from
var from = $stateParams["from"];$state.go(from && from != "login" ? from : $rootScope.defaultPage);
更多關(guān)于AngularJS相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《AngularJS入門與進(jìn)階教程》及《AngularJS MVC架構(gòu)總結(jié)》
希望本文所述對大家AngularJS程序設(shè)計有所幫助。
新聞熱點
疑難解答