1

I am still new to angular so sorry if my question is a little ...
I created a service that invoke some REST API and I implemented it with promises.

I am currently with this promise return list of data to controller and put it in $scope.

I want that when I receive data in this function also store retrived data to
service so I don't have to invoke service again if I already have data.

app.service("MyService", function ($http, $q) {
 this.OrignalDataFromService = null;
 return {
    var deferred = $q.defer();
    ...
    deferred.resolve(data);
    this.OrignalDataFromService = data;
    return deferred.promise;
  }
}

Problem with this is that when I access OrignalDataFromService from controller it is always undefined (in promise I get data it's just service variable that is undefined) why is that?
I don't understand really where should model reside in angular app.
Is it $scope variable in controller and services are just here to allow us to get data from somewhere, or should model be inside service (as a variable)?

1110
  • 7,829
  • 55
  • 176
  • 334

2 Answers2

3

OrignalDataFromService is private variable for service, so if you want can access it you need return in object

check this

example:

 app.service("MyService", function ($http, $q) {
 this.OrignalDataFromService = null;
 return {
    originalData: this.OrignalDataFromService
  }
}
Community
  • 1
  • 1
aseferov
  • 6,155
  • 3
  • 17
  • 24
1

Take a look at the fiddler here. You will have to expose the variable in which you are keeping the original data.

Service

myApp.service('myService', function($q) {
  return {
    OrignalDataFromService: null,
    getData: function() {
      var deferred = $q.defer();
      var data = ["Data-1", "Data-2", "Data-3"]
      deferred.resolve(data);
      this.OrignalDataFromService = data;
      return deferred.promise;
    }
  }
});
Pratik Bhattacharya
  • 3,596
  • 2
  • 32
  • 60