39

Angular のファクトリとサービスの概念を理解しようとしています。コントローラーの下に次のコードがあります

init();

    function init(){
        $http.post('/services', { 
            type : 'getSource',
            ID    : 'TP001'
        }).
        success(function(data, status) {
            updateData(data);
        }).
        error(function(data, status) {

        });

        console.log(contentVariable);
    };
    function updateData(data){
        console.log(data);
    };

このコードは正常に動作します。しかし、$http サービスをファクトリに移動すると、データをコントローラーに戻すことができません。

studentApp.factory('studentSessionFactory', function($http){
    var factory = {};
    factory.getSessions = function(){
        $http.post('/services', { 
            type : 'getSource',
            ID    : 'TP001'
        }).
        success(function(data, status) {
            return data;
        }).
        error(function(data, status) {

        });
    };
    return factory;
});

studentApp.controller('studentMenu',function($scope, studentSessionFactory){
    $scope.variableName = [];
    init();
    function init(){
        $scope.variableName = studentSessionFactory.getSessions();
        console.log($scope.variableName);
    };
});

$http はコントローラーの下でも機能するため、ファクトリを使用する利点はありますか

4

2 に答える 2

91

コントローラーからサービスを移動する目的は、studentSessions関心の分離を実現することです。サービスの仕事はサーバーとの対話方法を知ることであり、コントローラーの仕事はビュー データとサーバー データの間の変換です。

しかし、非同期ハンドラーと何が何を返しているのかを混乱させています。コントローラーは、データが後で受信されたときに何をすべきかをサービスに伝える必要があります...

studentApp.factory('studentSession', function($http){
    return {
        getSessions: function() {
            return $http.post('/services', { 
                type : 'getSource',
                ID    : 'TP001'
            });
        }
    };
});

studentApp.controller('studentMenu',function($scope, studentSession){
    $scope.variableName = [];

    var handleSuccess = function(data, status) {
        $scope.variableName = data;
        console.log($scope.variableName);
    };

    studentSession.getSessions().success(handleSuccess);
});
于 2013-04-26T02:24:50.963 に答える
10

最初の答えは素晴らしいですが、これを理解できるかもしれません:

studentApp.factory('studentSessionFactory', function($http){
    var factory = {};

    factory.getSessions = function(){
        return $http.post('/services', {type :'getSource',ID :'TP001'});
    };

    return factory;
});

それで:

studentApp.controller('studentMenu',function($scope, studentSessionFactory){
      $scope.variableName = [];

      init();

      function init(){
          studentSessionFactory.getSessions().success(function(data, status){
              $scope.variableName = data;
          });
          console.log($scope.variableName);
     };
 });
于 2015-04-28T11:57:33.777 に答える