数据检索在控制器内工作,但在我使用服务时不起作用 - AngularJS

时间:2016-06-21 17:12:11

标签: angularjs

我正在实现一些功能,以从数据库中检索员工列表,以便在我的AngularJS应用程序中显示。我创建了一个当前工作的控制器,如下所示:

 $scope.getEmployee = function () {
        $http.get("EmpWebService.asmx/GetEmp")
        .then(function (response) {
            $scope.employees = response.data;
        });
    }

我尝试将此逻辑移到服务中但数据返回undefined。这很奇怪,因为这几天前工作正常,但突然之间似乎没有起作用。这是代码:

控制器

$scope.getEmployee2 = function () {
        $scope.employees = fetchEmpService.fetchEmp();
    }

Service.js

fetchEmp: function () {
            debugger;
            return $http.get("EmpWebService.asmx/GetEmp")
                .then(function (response) {
                    return response.data;

                });
        }

2 个答案:

答案 0 :(得分:2)

上面的代码不起作用,因为fetchEmp将返回一个promise,因此$ scope.employees是一个承诺而不是员工列表,尝试这样做,

$scope.getEmployee2 = function () {
    fetchEmpService.fetchEmp().then(function (employeeList){
        $scope.employees = employeeList;
    });
}

答案 1 :(得分:1)

fetchEmpService.fetchEmp()返回一个promise。您可以在成功回调中从此服务访问employees对象。

$scope.getEmployee2 = function () {
   fetchEmpService.fetchEmp()
    .then(function(emp){
        $scope.employees = emp;
    });
}