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

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

问题描述

我想了解工厂,服务于角的概念。我有以下的code控制器在

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

这code正常工作。但是,当我移动$ 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天全站免登陆