Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call angular service method from controller?

I'm bit new in angular. I've built 'Employee Search' Service module. Here is the code...

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

Then, I'm using following code in my Controller to fetch data from this Service module.

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

I can see from my chrome console that, I'm getting data from my AJAX call with all console message from Service module. But, can't able to catch those data in Controller variable.

I think the way, I'm using 'searchEmpList()' & 'fetchEmpList()' in my controller it's not the right way. But, can't able to find out how to modify that one.

Need Some Guidance -.-

--- Controller Code updated ----

// 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});
    }
});
like image 870
Suresh Avatar asked Nov 19 '15 10:11

Suresh


1 Answers

this also seems confusing for me. the $http call s done asynchronously so when you call fetch it fetches an empty array. I would do something like this

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

and in the controller

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

Also notice that you have to return the $http in order to use .then() in the controller ( returns a promise).

Fot a great styleguide for angular check

like image 160
koox00 Avatar answered Oct 01 '22 02:10

koox00