2015-05-29 18 views
0

我有一個登錄頁面。登錄後我保存用戶價值爲會話存儲一樣如果LocalStorage值爲空,則更改位置

localStorage.setItem("user", something); 

成功登錄後,我改變$location.path('/something')。在此頁面中,我分配了$scope.user=localStorage.getItem("user")。如果用戶刪除歷史記錄並重新加載成功的登錄頁面(/something),則會出現錯誤。

我想這樣的:

if (!localStorage.getItem("user")) { 
    $scope.$apply(function(){ 
     $location.path('/'); 
    }) 
} 

但它不工作。我該如何解決這個問題?

+0

我看到你的代碼2點的問題。 $ locaion.path('/ something')中的拼寫錯誤 - 應該是$ location.path('/ something')。第二個 - localStorage只能存儲字符串,所以你應該串聯和解析JSON以使用localStorage。 – Mikalai

+0

@ Mikalai。感謝您找到錯別字。但這不是我的實際代碼。實際的一點是比較長的。在我的實際代碼中沒有錯別字,我也使用JSON.stringify存儲字符串。 – Arunkumar

+0

$ scope。$ apply(function(){ $ location.path('/'); }) - 在這裏你不需要$ apply – Mikalai

回答

0

你可以這樣做:

if(typeof localStorage.getItem("user") === 'undefined') { 
    //do redirect 
} 
+0

檢查不是問題。它(!localStorage.getItem(「user」))提醒真實。當用戶清除歷史記錄並重新加載頁面時。 – Arunkumar

相關問題