2013-04-26 159 views
37

我想了解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的作品,即使在控制器

回答

88

移動你的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); 
}); 
+1

謝謝Brian。現在有道理。在屬性列表錯誤後,我收到了一個'missing}錯誤。關閉添加一個關於工廠返回的參數後,錯誤仍然存​​在。 – 2013-04-26 02:54:54

+0

Oki修復了patrolhesis部分。現在代碼是'studentApp.factory'('studentSession',function($ http){ return { getSessions:function(){ return $ http.post('/ services',{ type:'getSource', ID:'TP001' }); } } });'現在有一個錯誤,說明錯誤b不是函數。我沒有任何稱爲b的功能。任何有關觸發此錯誤的建議? – 2013-04-26 04:17:47

+0

謝謝。我錯過了那個大括號。至於「b不是函數」,你是在使用某種代碼縮小或uglification? – 2013-04-26 10:29:40

8

第一個答案是偉大的,但也許你能明白這一點:

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); 
    }; 
}); 
+0

看起來像一個很好的答案,但'.success'現在已被棄用似乎http://stackoverflow.com/questions/33531336/angularjs錯誤成功 - 是 - 不是 - 一個功能#33531521。 – SharpC 2017-04-03 12:15:56