Sridhar
Sridhar

Reputation: 149

How to set and get a value in a service - angularjs

I have written a service described below

myApp.service('dashboardPath', function(){


    var path;

      return {
        path: path
      }

      this.path = function(value){
        path = value;
      }

});

am setting the value of path in sessionsCtrl like this dashboardPath.path = "student_dashboard" and i can access the value of path in any controller like dashboardPath.path which is returning the correct value, but if i reload the page the value of path is gone(it says "undefined"). Is my above service defined properly?

Upvotes: 1

Views: 111

Answers (3)

Luis Masuelli
Luis Masuelli

Reputation: 12343

this code looks strange:

myApp.service('dashboardPath', function(){

    var path;
    return {
        path: path
    }
    this.path = function(value){
        path = value;
    }

});
  1. return sentences are not needed since such function is called using new operator. yoor code should be:

    myApp.service('dashboardPath', function(){
    
        var path;
    
        this.path = path;
    
    });
    
  2. you need to -actually- store the value. By having it in just a variable, the context will be reset when you refresh, and you will still get the undefined you say. You should store it in one of three places:

    • server-side: use ajax ($http) to get and post the value.
    • client-side LocalStorage - See @bto.rdz's comment
    • cookies

    in any of such places you'll need to have a setter and getter for such values:

    this.getPath = function(){ ... };
    this.setPath = function(v){ ... };
    

    instead of the plain member variable path.

Upvotes: 0

SoluableNonagon
SoluableNonagon

Reputation: 11752

When you refresh the page the value will disappear because the app reloads. What you need is persistence of data:

myApp.service('dashboardPath', function(){

    var path = JSON.parse(localStorage.getItem('path'));
    this.path = function(value){
        path = value;
        localStorage.setItem("path", path);

      };

      return {
        path: path
      }

});

Upvotes: 2

Stuart Nelson
Stuart Nelson

Reputation: 4202

Services are singleton objects that will live for the duration of your application. Refreshing the page reloads all the code and ditches the old memory. Your code is working correctly.

If you want to persist data between page refreshes, try using localStorage.

Upvotes: 0

Related Questions