AngularJS:工厂$http服务

40

我试图理解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 甚至可以在控制器下工作?

2个回答

92
将您的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。现在我明白了。我得到了一个“属性列表后缺少}”的错误。即使在工厂中添加了一个闭合括号以返回,错误仍然存在。 - de-bugged
1
我正在使用压缩版的AngularJS。将尝试切换到普通版本。谢谢。 - de-bugged
太棒了,谢谢你...这正是我一直在尝试理解的概念。 - markstewie
@de-bugged 你之前遇到那个错误是因为这里的依赖是隐式的。在他们的文档中,它明确指出应该避免使用它,因为它会与最小化/混淆器产生问题。【Angular 文档】(https://docs.angularjs.org/guide/di) - Matheus
我没有使用任何缩小工具,它还会抛出get不是函数的错误。当我在控制台记录它时,它显示它没有作为带有函数的对象返回,而只是一个函数。 - ditoslav
显示剩余2条评论

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

看起来是一个不错的答案,但是似乎.success现在已经被弃用了。https://dev59.com/C1wX5IYBdhLWcg3wrBB6。 - SharpC

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接