0

I have a factory named readingService the factory method GetLastSyncTimestamp return a DateTime from a web service, after calling the factory I have assign return DateTime in $scope.lastSyncTimestamp variable, but problem is inside the promise I can get the DateTime correctly

 readingService.GetLastSyncTimestamp($scope.id).then(function(d) {
            $scope.lastSyncTimestamp = d.data;
            console.log($scope.lastSyncTimestamp);
        });

but outside the promise I don't get any data

 readingService.GetLastSyncTimestamp($scope.id).then(function(d) {
            $scope.lastSyncTimestamp = d.data;
        });

console.log($scope.lastSyncTimestamp);

is there any way to get data outside the promise ?

Mostafiz
  • 7,243
  • 3
  • 28
  • 42

2 Answers2

1

Create a service

  .service('DataService', function () {
            var service = {};
            service.defaultvalue= "1";
            return service;
        })

and inject it in the controller. Then you can use it in the promise like:

dataservice.lastSyncTimestamp = d.data;

and also outside will be working.

example: https://github.com/leader80/angularjs-dataservice/blob/master/js/dataService.js

thegio
  • 1,233
  • 7
  • 27
1

In this example:

readingService.GetLastSyncTimestamp($scope.id).then(function(d) {
    $scope.lastSyncTimestamp = d.data;
});

console.log($scope.lastSyncTimestamp);

The promise is not returning before the console.log($scope.lastSyncTimestap); line is executed. You can either handle the data within the promise or encapsulate the functionality you wish to do with the data in a function and call that function from within the promise.