Kartik Khandelwal Kartik Khandelwal - 4 months ago 14
AngularJS Question

service and controller in angular.js

app.factory('actfactory', function ($http) {
var myservice = {
result: [],
getdata: function () {
$http.get('api calll !!')
.success(function (response) {
console.log(response.data);
myservice.result.push(response.data);
}).error(function () {
if (window.localStorage.getItem("activity") !== undefined) {
self.results.push(JSON.parse(window.localStorage.getItem("activity")));
}
alert("please check your internet connection for updates !");
});
}
};


this is my controller

app.controller("activity", function ($scope,actfactory) {
$scope.activityresult = actfactory.getdata();
console.log( $scope.activityresult);
});


While doing console.log() in controller in am getting empty object !
and my service is console is returning fine response ?

HOW to get the result in controller of the service

Answer

the problem is since the javascript is asynchronous it does't wait until the actfactory.getdata() returns. before the $scope.activityresul get assign console.log( $scope.activityresult); gonna execute. the solution is use callback and wait until the factory returns

app.controller("activity", function ($scope,actfactory) {
   $scope.activityresult = actfactory.getdata(function(){
       console.log( $scope.activityresult);
   });
 });

app.factory('actfactory', function ($http) {
  var myservice = {
    result: [],
    getdata: function (callback) {
      $http.get('api calll !!')
        .success(function (response) {
          console.log(response.data);
          myservice.result.push(response.data);
          callback()
        }).error(function () {
        if (window.localStorage.getItem("activity") !== undefined) {
          self.results.push(JSON.parse(window.localStorage.getItem("activity")));

        }
        alert("please check your internet connection for updates !");
        callback()
      });
    }
  };
Comments