簡體   English   中英

在 Angular Js 中使用本地存儲

[英]Use Local Storage in Angular Js

我正在使用 angular js 開發應用程序。 我在使用本地存儲時遇到問題。 我的代碼看起來:

var id = response.data[0].id;
var email = response.data[0].email;
localStorage.setItem('userId', id);
localStorage.setItem('email', email);

我在 localstorage 中設置了兩個值。我在運行函數中獲取這些值

run(function($rootScope,$location) {           
    var userId = localStorage.getItem('userId');

    $rootScope.$on('$locationChangeStart', function (event, next, current) {
        alert(userId);
    });         
})

我的問題是 userId 在我刷新頁面時第一次顯示為 null 然后它提醒我值。 我如何在沒有刷新頁面的情況下獲得價值。

我得到了解決方案。問題是我在 $locationChangeStart' 方法之外獲得了 localstorage。

這是正確的方法:

run(function($rootScope,$location) {           
    $rootScope.$on('$locationChangeStart', function (event, next, current) {
       var userId = localStorage.getItem('userId');
        alert(userId);
    });         
})

我不知道它是否有幫助,但我找到了這個本地存儲示例。 您可以打開兩個頁面,兩個頁面都會根據另一個頁面進行更新。 本地存儲示例您會在右下角找到源代碼的鏈接。

$window.localStoage.setItem("key","Value");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM