The Angular JS controller failing to trigger the Spring MVC function

I'm currently working on integrating Angular JS with an existing Spring MVC project and encountering an issue when calling a Spring controller from the Angular JS controller.

Here is a snippet of my app.js:

'use strict';
var AdminApp = angular.module('AdminApp',[]);

And the service code:

'use strict';

AdminApp.factory('AdminService', ['$http', '$q', function($http, $q) {
    return {
        fetchAllTerminals: function() {
            return $http.get('http://localhost:8081/crmCTI/admin/terminal')
                    .success(function(response) {
                        console.log('Service');
                        return response.data;
                    })
                    .error(function(errResponse) {
                        console.error('Error while fetching terminals');
                        return $q.reject(errResponse);
                    });
        }
    };
}]);

and the controller setup:

'use strict';

AdminApp.controller('AdminController', ['$scope', 'AdminService', function($scope, AdminService) {
    var self = this;
    self.terminal={id:'',connectedUser:'',type:'',state:''};
    self.terminals=[];

    self.fetchAllTerminals = function() {
        console.log('Controller');
        AdminService.fetchAllTerminals()
        .success(function() {
            self.terminals = d;
        })
        .error(function() {
            console.error('Error while fetching Terminals');
        });
    };

    self.reset = function() {
        self.terminal = {id : null, connectedUser : '', type : '', state : ''};
    };
}]);

The JSP used for displaying data is as follows:

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<html>
<head></head>

<body ng-app="AdminApp" ng-init="names=['Jani','Hege','Kai']">
    <div ng-controller="AdminController as adminController">
        <table>
            <thead>
                <tr>
                    <th>Id</th>
                    <th>Login</th>
                    <th>Type</th>
                </tr>
            </thead>
            <tbody>
                <tr ng-repeat="terminal in adminController.terminals">
                    <td>{{terminal.id}}</td>
                    <td>{{terminal.connectedUser}}</td>
                    <td>{{terminal.type}}</td>
                </tr>
            </tbody>
        </table>
    </div>

    <script type="text/javascript" src="${pageContext.request.contextPath}/vendors/angular/1.4.4/angular.js"></script>
    <script type="text/javascript" src="${pageContext.request.contextPath}/js/app.js"></script>
    <script type="text/javascript" src="${pageContext.request.contextPath}/js/controller/admin-controller.js"></script>
    <script type="text/javascript" src="${pageContext.request.contextPath}/js/service/admin-service.js"></script>
</body>
</html>

While I can access my Spring Controller directly through a web browser and see the data, it seems that the Angular JS controller is not able to call it successfully.

Any suggestions or insights would be greatly appreciated!

Thank you for your help!

Answer №1

When retrieving data from a service function, it is recommended to utilize the .then function, as it has the capability to return data once the promise is resolved or rejected. This functionality cannot be achieved with the deprecated .success & .error functions.

The use of .success & .error methods of $http has been marked as **deprecated

Factory

AdminApp.factory('AdminService', ['$http', '$q', function($http, $q) {
    return {
        fetchAllTerminals: function() {
            return $http.get('http://localhost:8081/crmCTI/admin/terminal')
                    .then(function(response) {
                        console.log('Service');
                        return response.data;
                    },function(errResponse) {
                        console.error('Error while fetching terminals');
                        return $q.reject(errResponse);
                    });
        }
    };
}]);

In the controller method, another .then function should be applied to the factory method. The first function of .then will execute upon successful resolution of the fetchAllTerminals call, and the second function will handle rejections.

Controller

self.fetchAllTerminals = function() {
    console.log('Controller');
    AdminService.fetchAllTerminals()
    .then(function(data) {
        self.terminals = data;
    }, function(error) {
        console.error('Error while fetching Terminals');
    });
};

Answer №2

Give this a shot:

'use strict';
angular.module('AdminDashboard',[]);

Here's the service:

'use strict';

angular.module('AdminDashboard').factory('AdminDataService', ['$http', '$q', function($http, $q) {
    return {
        getTerminalData: function() {
            return $http.get('http://localhost:8081/crmCTI/admin/terminal')
                    .then(function(response) {
                        console.log('Service');
                        return response.data;
                    })
                    .catch(function(errResponse) {
                        console.error('Error while fetching terminals');
                        return $q.reject(errResponse);
                    });
        }
    };
}]);

controller:

'use strict';

angular.module('AdminDashboard').controller('AdminPanelController', ['$scope', 'AdminDataService', function($scope, AdminDataService) {
    var vm = this;
    vm.terminal={id:'',connectedUser:'',type:'',state:''};
    vm.terminals=[];

    vm.fetchAllTerminals = function() {
        console.log('Controller');
        AdminDataService.getTerminalData()
        .then(function(data) {
            vm.terminals = data;
        })
        .catch(function() {
            console.error('Error while fetching Terminals');
        });
    };

    vm.reset = function() {
        vm.terminal = {id : null, connectedUser : '', type : '', state : ''};
    };
}]);

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

How can I utilize the Camera function in Cordova?

I am in the process of developing a Cordova app that will be compatible with both iOS and Android platforms. One of the key features of the app is the ability to display a camera within a specified frame. Below the camera frame, there will be a button labe ...

jQuerry's on method fails to respond to newly added elements through the clone() function

I always thought that jquery's on() function would handle events for dynamically added elements in the DOM, such as those added via ajax or cloning. However, I'm finding that it only works for elements already attached to the dom at page load. Cl ...

What steps should I take to ensure that the JSON data is exclusively accessible to my JavaScript code?

Creating a web application that requires visualizing a significant amount of data using Charts. Discovered some interesting javascript libraries [dynagraph] that can handle this task. However, encountering an issue with using javascript to access data in J ...

Creating a slider that is reminiscent of the Amazon product slider: A step-by-step guide

I am in the process of building a website, but I lack skills in js and jQuery. I have been searching for days trying to find a library that supports the feature I need - zoom and thumbnails similar to Amazon or eBay product listing slider. However, most of ...

Deciphering key-value pairs that are separated by commas

I am looking to convert the following format: realm="https://api.digitalocean.com/v2/registry/auth",service="registry.digitalocean.com",scope="registry:catalog:*" Into this JSON object: { realm: "https://api.digitaloce ...

The timestamp indicating when the local file was last modified, using JavaScript

My current JavaScript project involves reading XML files stored in the %appdata% directory using jQuery's $.ajax function. Because the file is located in %appdata%, my JavaScript code has the necessary permissions to read and write to the file. For e ...

Are HTML tables a viable fix for the problem with ng-repeat?

Let's talk about a fictional dataset that mirrors tabular data found in Excel. function SU(name: String, data: Array<any>) { this.name = name, this.data = data }; function Month(month: String, year: String, goal: Number, projection: ...

Navigation list not displaying content on mobile devices as expected

Seeking assistance to resolve an issue with a responsive navigation bar implementation on my blog. Despite the presence of links in the navigational menu at 768px, they are not visible when inspected using Chrome. Here is an image for reference: Please See ...

Cracked Code at Position 880 (LeetCode)

Given an encoded string S, the decoded string is determined by reading each character and following the steps below: If the character is a letter, it is written directly onto the tape. If the character is a digit (denoted as d), the current tape i ...

Flexbox helps create responsive layouts with ease

Utilizing flex to centrally position my element within my layers has worked well for me, but I encountered an issue when switching to a smaller screen size. The element simply scales down in size instead of taking up the full width like it does with Bootst ...

Creating a sequence of dependent HTTP requests in Angular

Is it possible to execute multiple http get requests sequentially in Angular, where the endpoint URL for the second request depends on the response of the first request? I attempted to nest the requests using the following code snippet: this.http.get(end ...

The Vue template is not able to recognize the Pug language syntax within the .vue file

According to the Vue documentation: Template processing differs from other webpack loaders, as pug-loader and similar template loaders return a function instead of compiled HTML. Instead of using pug-loader, opting for original pug is recommended. Test ...

Guide for running an await function consecutively with JavaScript and React

I have the following code snippet: const somePromises = values.map(({variable, value}) => this.post('/api/values/', { variable, value, item: itemId, }) ); await Promise.all(somePromises); if (somecondition) { ...

jquery-powered scrollable content container

<script language="javascript"> $(document).ready(function($) { var methods = { init: function(options) { this.children(':first').stop(); this.marquee('play'); }, play: function( ...

Limit the number of Twitter Bootstrap popup tooltips to one using Jquery, ensuring only one instance of the popup is displayed at

Here is some HTML code that I am working with: <table class="bag"> <tr> <td id='slot0' item-type="" item-id=""> <a href="#" id="tool1" rel="popover" data-content="cont" data-original-title="ti-ta" da ...

Error SRVE0199E: The output stream has already been obtained while calling $.getJSON

Currently, I am working on a project using Spring 4.0.2 and WebSphere Application Server (WAS) 7. My goal is to retrieve a JSON object from a Spring servlet. The response should be straightforward, and I don't believe the error lies in any syntax iss ...

The rendering of the component is experiencing issues when using react-router

function App() { return ( //Following BEM naming convention <div className="app"> <div className="app__body"> <Sidebar /> <Chat /> <Router> <Routes> ...

Which event in the listbox should I trigger to adjust the scroll position?

My webpage includes a listbox inside an update panel. I've managed to capture the scroll position, but now I'm facing difficulty in identifying the right javascript event to call my function for setting the scroll position after the update panel ...

Retrieve the outcome of a mongoose query within a designated function

Seeking help with returning a result from my mongoose find operation. While similar questions have been asked before, this one is unique. Here's an example of my user: let UserSchema = new mongoose.Schema({ variable: {type: mongoose.Schema.Object ...

Experiencing Strange Issues with Jquery Image Carousel... Assistance Needed!

I recently created a jquery slideshow using a tutorial I found at this link: While the slideshow is functioning correctly for the most part, there is a strange issue that occurs right at the beginning when displaying the first image. Initially, the first ...