2016-07-14 134 views
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 !"); 
     }); 
    } 
    }; 

這是我的控制器服務和控制器angular.js

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

雖然控制器做的console.log()在我得到空的對象! 和我的服務是控制檯返回罰款響應?

如何獲得的結果在服務

回答

0

問題是因爲javascript是異步的,它不會等到actfactory.getdata()返回。在$scope.activityresul得到分配console.log($scope.activityresult);將執行。解決方法是使用回調並等待,直到出廠退貨

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

使用承諾的控制器:

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

另外,從服務返回一個承諾:

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