如何从控制器调用角度服务方法?

时间:2015-11-19 10:18:24

标签: javascript angularjs angular-services

我在角度方面有点新鲜。我已经建立了“员工搜索”服务模块。这是代码......

// Service for employee search
app.service('employeeSearchService', function($http, resourceServerAddress){
    this.empList = [];

    // Method for clearing search employee list
    this.clearEmpList = function(){
        this.empList = [];
    }

    // Method for fetching employee search list
    this.fetchEmpList = function(){
        return this.empList;
    }

    // Method for making employee search
    this.searchEmpList = function(empName){
        var postData = {
                    empName:empName,
                };

        $http({
            method: 'POST',
            url: resourceServerAddress,
            data : postData
        }).then(function successCallback(response) {
            console.log('Response Data : '+response);

            if(response['data']['status'] === 'success'){
                console.log('Response received successfully with status=success');

                if(response['data']['data'].length)
                {
                    console.log('matches found for employee search');
                    this.empList = response;
                }
                else
                {
                    console.log('no matches found for employee search');
                    this.empList = [];
                }
            }

            if(response['data']['status'] === 'error'){
                console.log('Response received successfully with status=error');
            }

        }, function errorCallback(response) {
            console.log('Error occur at time of processing request');
        });
    }
});

然后,我在Controller中使用以下代码从此服务模块中获取数据。

employeeSearchService.searchEmpList(empName);
empSearchResponseList = employeeSearchService.fetchEmpList();
console.log('Search response from server module : '+empSearchResponseList);

我可以从我的chrome控制台看到,我从我的AJAX调用中获取数据,其中包含来自Service模块的所有控制台消息。但是,无法在Controller变量中捕获这些数据。

我想方式,我正在使用'searchEmpList()'&我的控制器中的'fetchEmpList()'不是正确的方法。但是,无法找出如何修改那个。

需要一些指导-.-

---控制器代码更新----

// Controller for application Home route
app.controller("HomeController", function($scope, $state, $location, $ionicHistory, $ionicSideMenuDelegate, $http, resourceServerAddress, employeeSearchService) {

    console.log('At home controller');

    // Check application session. If it's found not exist redirect user to login page
    if(window.localStorage.getItem("access_token") === "undefined" || window.localStorage.getItem("access_token") === null) {
        $ionicHistory.nextViewOptions({
            disableAnimate: true,
            disableBack: true
        });

        console.log('Redirecting user to login page-222');
        $state.go("login");
    }

    $scope.empName               = '';
    $scope.alertMsgBox           = false;
    $scope.alertMsgText          = '';
    $scope.employees             = [];
    $scope.resourceServerAddress = resourceServerAddress;

    var empSearchResponseList=null;

    // Method for employee search
    $scope.searchEmployee = function(form){
        console.log('Employee name entered : '+$scope.empName);
        console.log('Employee name character length : '+$scope.empName.length);

        if($scope.empName.length >= 3 ){

            var postData = {
                    Emp_Name:$scope.empName,
                    access_token:window.localStorage.getItem('access_token'),
                    session_id:window.localStorage.getItem('session_id')
                };

            $http({
                method: 'POST',
                url: resourceServerAddress,
                data : postData
            }).then(function successCallback(response) {
                console.log('Response Data : '+response);

                if(response['data']['status'] === 'success'){
                    console.log('Response received successfully with status=success');

                    if(response['data']['data'].length)
                    {
                        console.log('matches found for employee search');
                        $scope.employees   = response['data']['data'];
                        $scope.alertMsgBox = false;
                    }
                    else
                    {
                        console.log('no matches found for employee search');
                        $scope.alertMsgBox  = true;
                        $scope.employees    = [];
                        $scope.alertMsgText = 'No matches found.';
                    }
                }

                if(response['data']['status'] === 'error'){
                    console.log('Response received successfully with status=error');
                }

            }, function errorCallback(response) {
                console.log('Error occur at time of processing request');
            });
        }
    }


    // Method for showing employee profile
    $scope.showEmpProfile = function(empId){
        console.log('HomeCtrl - click on profile image of emp id : '+empId);

        // Redirecting to home page
        $state.go('app.emp-profile', {empId:empId});
    }
});

2 个答案:

答案 0 :(得分:4)

this对我来说似乎也很困惑。 $http调用是异步完成的,因此当您调用fetch时,它会获取一个空数组。 我会做这样的事情

this.searchEmpList = function(empName){
    var postData = {
                empName:empName,
            };

    return $http({
        method: 'POST',
        url: resourceServerAddress,
        data : postData
    }).then(function(response) {
        console.log('Response Data : '+response);

        if(response['data']['status'] === 'success'){
            console.log('Response received successfully with status=success');

            if(response['data']['data'].length)
            {
                console.log('matches found for employee search');
                return response['data']['data'];
            }
            else
            {
                console.log('no matches found for employee search');
                return [];
            }
        }

        if(response['data']['status'] === 'error'){
            console.log('Response received successfully with status=error');
        }

    }, function(response) {
        console.log('Error occur at time of processing request');
    });
}

并在控制器中

employeeSearchService.searchEmpList(empName).then(function(data){
    console.log('data is ready', data);
});

另请注意,您必须返回$http才能在控制器中使用.then()(返回承诺)。

Fot for angular check

的伟大风格指南

答案 1 :(得分:1)

您确定服务有效吗? 我更喜欢这种语法:

  .service('Service', function () {
    var Service = {
        //methods here
    }
    return Service;
  });

你不需要努力工作' this '。