8

以下のように定義されたコントローラーとファクトリーがあります。

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を通じて、ファクトリの使用に関するこの情報を見つけました。

4

2 に答える 2

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;
     }
 });
于 2013-07-29T21:28:50.633 に答える
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
});

それが役に立てば幸い

于 2015-02-04T05:21:27.077 に答える