简体   繁体   English

在AngularJS中设置会话

[英]Setting up a session in AngularJS

I want to transfer an object from one page to another. 我想将一个对象从一个页面转移到另一个页面。 It's a search results page when clicking on a result it leads to a page needed. 这是一个搜索结果页面,当点击它导致所需页面的结果时。 So I need to transfer the object which has data of the required result. 所以我需要传输具有所需结果数据的对象。

I tried using services and factory but the data gets reset whenever I loaded the next page 我尝试使用服务和工厂,但每当我加载下一页时数据都会重置

Also I would need to store client details for other pages too, So I think sessions are a better choice 此外,我还需要存储其他页面的客户端详细信息,所以我认为会话是更好的选择

It is not possible without server intervention. 没有服务器干预是不可能的。 If you want to share the data on client itself, you need to use Local or Session Storage, which store the information as key-value pairs. 如果要在客户端本身共享数据,则需要使用本地或会话存储,它将信息存储为键值对。

To set an item in the local storage 在本地存储中设置项目

window.localStorage.setItem("key", "value");

To get an item from the local storage 从本地存储中获取项目

window.localStorage.getItem("key"); // returns "value"

Local storage is persisted until the browser/you manually clean it. 本地存储一直持续到浏览器/您手动清理它。 On the other hand, session storage is cleared as soon as the tab/window is closed. 另一方面,只要选项卡/窗口关闭,会话存储就会被清除。

More details here . 更多细节在这里

There are few ways, here is one among them. 几种方法,其中一种是其中之一。 You can use localStorage if you want to trade minor objects or variables across the application. 如果要在整个应用程序中交换次要对象或变量,可以使用localStorage。

You can set the object in a localStorage as below 您可以在localStorage中设置对象,如下所示

localStorage.setItem('objectNameAsKey', realObjectReference);

You can also stringify the JSON object if needed. 如果需要,您还可以对JSON对象进行字符串化。

 localStorage.setItem('objectNameAsKey', JSON.stringify(realObjectReference));

Wherever you need this object, you can get it using the key 无论您何时需要此对象,都可以使用密钥获取它

localStorage.getItem('objectNameAsKey'); 

When you fetch the stringify'd object, you can do as below, 当您获取stringify'd对象时,您可以执行以下操作,

JSON.parse(localStorage.getItem('objectNameAsKey'));

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

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