AngularJS : factory $http service

11 浏览
0 Comments

AngularJS : factory $http service

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

0