AngularJS:工厂 $http 服务 [英] AngularJS : factory $http service

查看:31
本文介绍了AngularJS:工厂 $http 服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图理解 Angular 中工厂和服务的概念.我在控制器下有以下代码

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

此代码工作正常.但是当我将 $http 服务移入工厂时,我无法将数据返回给控制器.

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

使用工厂有什么好处,因为 $http 甚至在控制器下也能工作

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

推荐答案

studentSessions 服务移出控制器的目的是实现关注点分离.您的服务的工作是知道如何与服务器通信,而控制器的工作是在视图数据和服务器数据之间进行转换.

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

这篇关于AngularJS:工厂 $http 服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆