2013-07-29 201 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 
}); 

希望它可以幫助