0

I have done this before, but this time dont know what went wrong.

A service:

angular.module('module')
  .service("BaseService", function() {
    var vm = this;
    var testValue = {a:1,b:2};
    vm.getTestValue = function(){
        return testValue;
    }
  });

A method in a Controller:

vm.getTest = function(){
      console.log(BaseService.testValue) // undefined - cool
      console.log(BaseService.getTestValue()) //{a: 1, b: 2} - cool
      var value = BaseService.getTestValue();
      console.log(value) // {a: 1, b: 2} - cool
      value.a = 20; // updated local object
      console.log(value) // {a: 20, b: 2} -cool
      console.log(BaseService.getTestValue())-- {a: 20, b: 2} -- ??? why
}

Hope my question is clear, why a local variable is getting updated within service and if it behaves like that..what's the proper way of getting setting functions in services/factories....would it be better to prototyping functions rather appending fuctions in vm.

Luckyy
  • 1,021
  • 4
  • 15
  • 29

1 Answers1

0

Your variable (testValue) in the service is an object which belongs to the reference types. When you use it in the controller it gets only the reference, the object remains the same. You actually have 2 reference to the same object, so changing it's properties via the one of the references affects the object. So you get the changed object.

Imagine a room with two doors. Here doors are your references and the room is the object itself. When you come in through one door and change something in the room, then coming in from the another one you can see the changes in the room.

If you don't want to get the current object, you can copy the object in the function and return the copy.

vm.getTestValue = function() {
    return angular.copy(testValue);
}
Suren Srapyan
  • 66,568
  • 14
  • 114
  • 112
  • Thanks Suren....that's what I am doing as an alternative...but would like to know the best way to deal with these objects...and thanks for the example of rooms...its very innovative and easy to remember – Luckyy Oct 04 '17 at 05:45
  • If you don't need to change your object, you must make the the function immutable, so you need to return the copy. – Suren Srapyan Oct 04 '17 at 05:49