1
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

2 Answers 2

3

Use a promise:

actfactory.getdata().then(function(data) {
    $scope.activityresult = data;
    console.log( $scope.activityresult);
});

Also, return a promise from your service:

return $http.get('api calll !!')
    .success(function (response) {
      console.log(response.data);
      myservice.result.push(response.data);
      return 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 !");
  });
Sign up to request clarification or add additional context in comments.

Comments

0

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.