AngularJS : factory $http service

后端 未结 2 1602
一整个雨季
一整个雨季 2020-12-02 09:37

I am trying to understand the concept of factory and service in Angular. I have the following code under the controller

init();

    function init(){
                


        
相关标签:
2条回答
  • 2020-12-02 10:01

    The first answer is great but maybe you can understand this:

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

    Then:

    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 讨论(0)
  • 2020-12-02 10:02

    The purpose of moving your studentSessions service out of your controller is to achieve separation of concerns. Your service's job is to know how to talk with the server and the controller's job is to translate between view data and server data.

    But you are confusing your asynchronous handlers and what is returning what. The controller still needs to tell the service what to do when the data is received later...

    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);
    });
    
    0 讨论(0)
提交回复
热议问题