Thursday, February 20, 2014

$CacheFactory and localStorage

In a web application if we want to store and retrieve some value in the client browser cookies used to be best solution.  However because of the size limitation of the cookie  HTML5 web storage is the solution that we have presently. Web storage is more faster and secure. The size limit of it is 5MB.

The HTML 5 web storage is natively built into modern browsers. One example of this is below:

//To store values
 localStorage . setItem("firstName", "Mike");
//To retrieve values
var name=localStorage. getItem("firstName");
//If you print the localStorage now
//The output to the above statement will be
//Storage {firstName: "Mike", length: 1}

 The local storage data stays in browser even if after you close the browser, so it's not related to the user session.

 AngularJS has one service called $Cachefactory, which you can use for similar purpose however  it's available to your Angular application only.

 Below is one example for that:

var myCache = $cacheFactory('cache_1');
myCache.put("lastname", "john");

var lastName = myCache.get("lastname");

 The output to the above statement will be

   * Object
   * id: "cache_12"
    *size: 1

No comments:
Write comments