Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
138 views
in Technique[技术] by (71.8m points)

javascript - AngularJS : factory $http service

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

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

This code works fine. But when i move $http service into factory, i am not able to return data back to controller.

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

Is there any advantage to using factory, since $http works even under controller

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.9k users

...