What is the best way to utilize an Angular service method from a controller?

As a newcomer to Angular, I have created an 'Employee Search' Service module. Let's take a look at the code:

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

    // Method to clear the employee search list
    this.clearEmpList = function(){
        this.empList = [];
    }

    // Method to fetch the employee search list
    this.fetchEmpList = function(){
        return this.empList;
    }

    // Method to perform an 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');
        });
    }
});

Next, in my Controller, I am using the following code to retrieve data from the Service module.

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

While I can see the data and console messages from the service module in Chrome console, I am unable to capture that data in the Controller variable.

I suspect that the way I am using 'searchEmpList()' & 'fetchEmpList()' in my controller may not be correct. I am struggling to find out how to modify it.

Seeking some guidance!

--- Updated Controller Code ---

// 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 none exists, 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');
        $state.go("login");
    }

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

    var empSearchResponseList=null;

    // Method for searching employees
    $scope.searchEmployee = function(form){
        console.log('Employee name entered : '+$scope.empName);
        console.log('Length of employee name : '+$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 to display employee profile
    $scope.showEmpProfile = function(empId){
        console.log('Clicked on profile image of employee ID : '+empId);

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

Answer №1

this is really puzzling for me. the $http call happens asynchronously, so when you invoke fetch, it ends up fetching an empty array. I propose 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 note that you need to return the $http to utilize .then() in the controller (returns a promise).

For a comprehensive styleguide on Angular, refer here

Answer №2

Do you have faith in the functionality of your service? I am inclined to use the following code structure:

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

Furthermore, there is no need for extensive utilization of 'this'.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The filtering feature in AngularJS ng-options is not functioning correctly

Greetings, I am a newcomer to angular. In my current demo application, I have created a list of users with a select filter using ng-option. There seems to be a bug that I have been unable to identify. The issue: When I select the Female option, i ...

Modifying element size using jQuery causes issues with maintaining a 100% height

I am facing an issue with a sidebar that is styled using the following css properties: background:#164272; position:absolute; left:0px; top:70px; width:250px; height:100%; When I use jQuery to display a table that is initially hidden and on ...

The percentage height setting for a div is not functioning properly, but setting the height in pixels or viewport

Within a dialog box body, I am attempting to display a table and have applied a CSS class to the wrapping div. When specifying the height in pixels or viewport height units, it works as expected. However, when using a percentage like 50%, the height of the ...

Managing errors in jQuery's .ajax function

Having some issues with jQuery.ajax() while trying to fetch an html code snippet from table_snippet.html and replacing the element in my html code. The error handler in jQuery.ajax() gets triggered instead of the expected success handler. <!DOCTYPE H ...

"Attempting to access a variable defined in one pipe results in it being undefined in a

Currently, I am utilizing gulp to process pages for a website. Some of these pages are PHP files, however, after going through the template engine, they all end up with a .html file extension. My intention is to add a property to each file indicating if it ...

Unable to view the refreshed DOM within the specifications after it has been altered

For my current project, I am working on writing a functional spec that involves using Mocha/JSDOM and making assertions with 'chai'. The specific use case I am tackling is related to the function called updateContent: When this function is exec ...

Juggling PHP scripts within javascript

Can you help me with a question I have? I am working on multiple JS scripts, such as this one: <script> $('#mapveto1').click(function() { $('#mapveto1').addClass('banned'); $('#map1').text('cobble ...

Effective strategies for minimizing the bundle size of your NextJs application

Recently, I launched my first NextJS app and was surprised to see that the initial bundle size is around 1.5Mb, which seems quite large for me as a beginner in using Nextjs. I have shared an image of the yarn build and also my package.json. All the pages ...

Execute a function upon pressing the enter key

Currently, I am working on coding a webpage with a form that includes one field where users input a set of numbers. After typing in the numbers, they should then press a button labeled 'Run' to execute the code. However, the issue arises when use ...

Issues occurred when attempting to access information with postgres and nodeJS

Below is the configuration I have set up in my files: const express = require('express') const app = express() const port = 8000 const expense_model = require('./expense_model') app.use(express.json()); app.us ...

Whenever I make a move in the Towers of Hanoi javascript game, I always ensure that both towers are updated simultaneously

As I explore the Towers of Hanoi puzzle using JavaScript constructors and prototypes, I encounter issues with my current implementation. Whenever I move a disc from one tower to another, an unintended duplicate appears in a different tower. Additionally, a ...

Compilation of Angular 6 project is failing due to error TS1005: Expected ',' instead of the symbol used

I keep encountering an error message whenever I try to compile my code. ERROR in src/app/form/form.component.ts(22,39): error TS1005: ',' expected. Below is the snippet of code where the error is pointing: import { Component, OnInit } from &ap ...

What is the process for obtaining a fresh token from Cognito using the frontend?

Currently, I am working with a react app that utilizes Cognito for user authentication. My main query revolves around making a call to Cognito using the refresh token in order to receive a new token. Despite researching various examples provided by Cognit ...

When using Vue.js and Quasar to implement multiple filtering forms, an issue arises where the input value disappears

I am currently exploring how to implement multi-item filtering in Quasar, a framework of Vue. At the moment, I am utilizing input and checkbox elements. Everything seems to be functioning correctly, but there is an issue with the select item disappearing. ...

The function HandleKeyPress is failing to recognize the input from the down arrow

I'm currently working on developing a customized and user-friendly select input using React.js. My goal is to have the functionality where the up and down arrow keys behave like the tab key within the context of selecting options. In order to achieve ...

Ways to remove all HTML elements from a string

Check out the code that I currently have: I am looking for a way to prevent users from entering any HTML tags in the "Add Responsibilities" field. For example, if a user enters the following: <div>Test</div> It should only display the text l ...

Angular - The answer to intricate router parameters management with hyperlink addresses

I have a unique feature in my card design where I want users to be able to open the content in a new tab by using their mouse's middle button. To achieve this, I added a link <a> with an automatically generated href for each card. However, there ...

Looking to incorporate content from an external website onto my own site

I have experimented with various types of HTML tags such as iframe, embed, and object to display external websites. Some of them load successfully, while others do not. After researching my issue on Google, I discovered that "For security reasons, some si ...

Ensuring correct association of values to avoid redundancies

There are 5 fields available for users to fill out on this form: Leave Code, From Date, Input Time1, To Date, and Input Time2. These variables are declared as a dates object in the .ts file, as shown below. interface Supervisor { name: string; code: s ...

Get the PDF file and access it with Ajax technology

I am facing an issue with my action class that is responsible for generating a PDF. The code snippet shown sets the contentType appropriately. public class MyAction extends ActionSupport { public String execute() { ... ... File report = si ...