Kartik Khandelwal
Kartik Khandelwal

Reputation: 47

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

Upvotes: 1

Views: 35

Answers (2)

Sachila Ranawaka
Sachila Ranawaka

Reputation: 41407

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()
      });
    }
  };

Upvotes: 0

Tarun Dugar
Tarun Dugar

Reputation: 8971

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 !");
  });

Upvotes: 3

Related Questions