AngularJS:从工厂

时间:2015-07-03 19:58:22

标签: angularjs promise angularjs-service angular-promise angularjs-factory

我有一个factory来从数据库中获取包含所有客户的数组。 然后我需要由人id过滤此数组,并在一个页面中仅显示它的数据。

我已经有了一个工作代码,但它只在controller内,我希望将它与factorydirective一起使用,因为我不再使用{{1}这个ng-controller已经调用了我需要显示客户端数据的其他页面。

这是我尝试使用factory

app.js

factory

detClient.html

app.factory('mainFactory', function($http){

    var getCliente = function($scope) {
        return $http.get("scripts/php/db.php?action=get_cliente")
        .success( function(data) {
            return data;
        })
        .error(function(data) {
        });
    };

    var getDetCliente = function($scope,$routeParams) {
        getCliente();
        var mycli = data;
        var myid = $routeParams.id;
        for (var d = 0, len = mycli.length; d < len; d += 1) {
            if (mycli[d].id === myid) {
                return mycli[d];
            }
        }
        return mycli;
    };

    return {
        getCliente: getCliente,
        getDetCliente: getDetCliente
    }
});

app.directive('detClienteTable', function (mainFactory) {
    return {
        restrict: "A",
        templateUrl: "content/view/det_cliente_table.html",
        link: function($scope) {
            mainFactory.getDetCliente().then(function(mycli) {
                $scope.pagedCliente = mycli;
            })
        }
    }
});

问题是,我无法在页面中显示任何数据,而且我的控制台中没有错误。

可能有什么问题?
请记住,我正在学习AngularJS。

2 个答案:

答案 0 :(得分:3)

基本上,您需要实现一个promise链,因为查看代码看起来就像是getCliente()承诺getDetCliente方法。在这种情况下,您需要使用.then功能,而不是使用.success&amp; .error,它不允许您继续保证链。在getDetCliente函数之后,您再次需要使用.then函数,当getCliente函数解析了他的承诺时,该函数会被调用。您的代码将使用表单重新格式化并返回mycli结果。

<强>代码

var getCliente = function() {
    return $http.get("scripts/php/db.php?action=get_cliente")
    .then( function(res) { //success callback
        return res.data;
    },function(err){ //error callback
       console.log(err)
    })
};

var getDetCliente = function(id) {
    return getCliente().then(function(data){
        var mycli = data;
        var myid = id;
        for (var d = 0, len = mycli.length; d < len; d += 1) {
           if (mycli[d].id === myid) {
              return mycli[d];
           }
        }
        return mycli;
    })
};

修改

你不应该将控制器$scope传递给与你的指令和控制器紧密耦合的服务。你也想传递路由的id参数然后你需要从指令传递它服务电话

link: function($scope) {
    mainFactory.getDetCliente($routeParams.id).then(function(mycli) {
        $scope.pagedCliente = mycli;
    })
}

答案 1 :(得分:1)

您正在getCliente中将getDetCliente视为同步通话。有趣的是,在您的指令中,您了解getDetCliente是异步的。将getCliente更改为此并在getDetCliente中调用它时将其视为异步调用:

var getCliente = function($scope) {
    return $http.get("scripts/php/db.php?action=get_cliente");
};