2013-07-29 101 views
8

我有一个控制器和工厂定义如下。角js从工厂返回undefined对象

myApp.controller('ListController', 
     function($scope, ListFactory) { 
    $scope.posts = ListFactory.get(); 
    console.log($scope.posts); 
}); 

myApp.factory('ListFactory', function($http) { 
    return { 
     get: function() { 
      $http.get('http://example.com/list').then(function(response) { 
       if (response.data.error) { 
        return null; 
       } 
       else { 
        console.log(response.data); 
        return response.data; 
       } 
      }); 
     } 
    }; 
}); 

什么让我困惑的是,我从我的控制器未定义输出,然后控制台输出的下一行是我从我的工厂对象的列表。我也试图改变我的控制器

myApp.controller('ListController', 
     function($scope, ListFactory) { 
    ListFactory.get().then(function(data) { 
     $scope.posts = data; 
    }); 
    console.log($scope.posts); 
}); 

但我收到错误

TypeError: Cannot call method 'then' of undefined 

注:我发现在使用工厂通过http://www.benlesh.com/2013/02/angularjs-creating-service-with-http.html

回答

8

您需要可以使用回调此信息功能或只是把之前的退货$http.get...

return $http.get('http://example.com/list').then(function (response) { 
    if (response.data.error) { 
     return null; 
    } else { 
     console.log(response.data); 
     return response.data; 
    } 
}); 
2

$ http.get是异步的,所以在你尝试访问它的时候(在你的控制器内)它可能没有数据(因此你得到了未定义)。

为了解决这个问题,我使用.then()从我的控制器调用工厂方法后。然后,您的工厂将类似于:

myApp.factory('ListFactory', function($http) { 
    return { 
     get: function() { 
      $http.get('http://example.com/list'); 
     } 
    }; 
}); 

而且你的控制器:

myApp.controller('ListController', function($scope, ListFactory) { 
    ListFactory.get().then(function(response){ 
     $scope.posts = response.data; 
    }); 
    // You can chain other events if required 
}); 

希望它可以帮助