source

Angular JS : 공장 출하시 $http 서비스

nicesource 2023. 2. 28. 23:37
반응형

Angular JS : 공장 출하시 $http 서비스

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는 컨트롤러 하에서도 동작하므로 팩토리를 사용하면 어떤 이점이 있습니까?

이동의 목적은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);
});

첫 번째 답변은 훌륭하지만 이해하실 수 있습니다.

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

언급URL : https://stackoverflow.com/questions/16227644/angularjs-factory-http-service

반응형