Shubham Bhardwaj
Shubham Bhardwaj

Reputation: 155

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

Upvotes: 1

Views: 28

Answers (2)

CrazyMac
CrazyMac

Reputation: 462

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.

You can set the object in a localStorage as below

localStorage.setItem('objectNameAsKey', realObjectReference);

You can also stringify the JSON object if needed.

 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,

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

Upvotes: 0

31piy
31piy

Reputation: 23859

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.

Upvotes: 3

Related Questions