angular.js中的服务和控制器

时间:2016-07-14 11:49:19

标签: angularjs

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

这是我的控制器

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

在控制器中执行console.log()时获取空对象! 我的服务是控制台正在返回精细响应?

如何在服务的控制器中获得结果

2 个答案:

答案 0 :(得分: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 !");
  });

答案 1 :(得分: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()
      });
    }
  };