Unable to retrieve data from SpringBoot controller using $http.get request

I have developed an application that will execute queries on my store's database based on user input on the webpage. The backend method is functioning correctly and returns the response, but I am having trouble displaying the data in a dynamic table on the webpage. I am new to AngularJS, so any assistance is greatly appreciated.

StoreController.java

@RequestMapping(value = "/runQuery", method = RequestMethod.GET)
public List<Map<String, Object>> runQuery(@RequestParam(value="query", defaultValue="* FROM items") String statement, Model model)  {
    List<Map<String, Object>> answer = storeService.executeUserQuery(statement);
    model.addAttribute("resultList", answer);
    return answer;
}

I have attempted to set up my controller to dynamically assign the Java controller data to the $scope variable.

app.module.js

(function(){
    'use strict';

    angular.module('app', []);
})();

store.controller.js

angular
.module('app').controller('StoreController', ['$scope','StoreService','StoreController','$q', function ($scope,StoreService, StoreController, $q) {

    $scope.runQuery = function () {

               StoreService.runQuery($scope.statement)
              .then (function (data){
                  $scope.rows = response.data;
                  $scope.cols = Object.keys($scope.rows[0]);
              },
              function error(response){
                  if (response.status == 404){
                  $scope.errorMessage = response.data[0];
              }
                  else {
                      $scope.errorMessage = 'Error displaying result user!';
                  }
            });
          }
    }

]);

app.service('StoreService',['$http', function ($http,$q) {

    this.runQuery = function runQuery(statement){
        return $http({
          method: 'GET',
          url: 'http://localhost:8080/runQuery/',
          params: {statement:statement},
          headers: 'Accept:application/json'
        }).then( function(response){
            return reponse.data;
        });
    }

index.html

<body data-ng-app="app" data-ng-controller="StoreController">
    <div class="container">

        <form th:action="@{/logout}" method="get">
            <button class="btn btn-md btn-danger btn-block"
                style="color: #fff; background-color: #e213a2; border-color: #c3c2c0;"
                name="registration" type="Submit">Logout</button>
        </form>

        <div class="panel-group" style="margin-top: 40px">
            <div class="panel panel-primary">
                <div class="panel-heading">
                    <span th:utext="${userName}"></span>
                </div>
                    <div>
                <form name="queryForm" method="get" data-ng-submit="runQuery()">
                    <div class="panel-body">
                        <h3 id="queryLabel">Select Query:</h3>
                        <textarea id="query" wrap="soft"
                            placeholder="Please do not enter SELECT with your query, it's added automatically!!" data-ng-model="statement"></textarea>
                        <button type="submit">Run Query</button>
                    </div>
                    </form>
                    <div class="panel-body" id="results">
                        <h3 id="queryLabel">Result:</h3>
                        <table border="1">
                            <tr>
                                <th data-ng-repeat="column in cols">{{column}}</th>
                            </tr>
                            <tr data-ng-repeat="row in rows">
                                <td data-ng-repeat="column in cols">{{row[column]}}</td>
                            </tr>
                        </table>
                    </div>

                </div>
                <div>
                    <p class="admin-message-text text-center" th:utext="${adminMessage}"></p>

                </div>
    </div>
    </div>
    </div>
</body>

The table on the html page, works because I received it from this link http://jsfiddle.net/v6ruo7mj/1/

But it's not populating the tables with the data received from my backend controller method. I do not have any entities as this is just querying an existing database, so I need not to add any entities.

Answer №1

The issue may lie in this particular line within the service callback of your controller:

.then (function (data){
    $scope.rows = response.data;
    // ...
}

Consider modifying it to:

.then (function (data){
    $scope.rows = data;
    // ...
}

You are already returning the response data in your service when using:

}).then( function(response){
        return response.data;
    });

On a separate note, it is worth mentioning that your Spring controller appears to be susceptible to SQL injection. It is generally not recommended to allow direct access to your database for users. Without understanding the implementation of your StoreService on the backend, it seems that an attacker could potentially manipulate your database by sending HTTP calls to your endpoint.

Answer №2

There is a mistake in the runQuery function:

app.service('StoreService',['$http', function ($http,$q) {

    this.runQuery = function executeQuery(sql){
        return $http({
          method: 'GET',
          url: 'http://localhost:8080/runQuery/',
          params: {sql:sql},
          headers: 'Accept:application/json'
        }).then( function(response){
            return response.data
        });
    }
 }]);

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

Initialization of an empty array in Typescript

My promises array is structured as follows: export type PromisesArray = [ Promise<IApplicant> | null, Promise<ICampaign | ICampaignLight> | null, Promise<IApplication[]> | null, Promise<IComment[]> | null, Promise<{ st ...

Arranging arrays of various types in typescript

I need help sorting parameters in my TypeScript model. Here is a snippet of my model: export class DataModel { ID: String point1: Point point2 : Point point3: Point AnotherPoint1: AnotherPoint[] AnotherPoint2: AnotherPoint[] AnotherPoi ...

Unable to locate the module name loaded using require() function

Within my React file, I am importing a Javascript file like this (I am using Typescript): let FloDialog = require('../public/js/flo-dialog.min'); Afterwards, I declare a property for the dialog class: dialog: FloDialog = null; It is important ...

div or paragraph element nested within a flex container

How can I make the logo text div tag, called Title, take up its content space inside the parent flexbox without wrapping? I prefer not to set the Title div to 100% or use white-space: nowrap. I simply want it to behave like a regular div where it fills it ...

Bring in a 3-dimensional model using JSONLoader in three.js

I'm facing some challenges with incorporating a simple 3D object created in Maya into my Three.js project using JSONLoader. The object consists of various materials (Lambert and Phong) and different colors. I used Maya to create a .obj file, then Ble ...

The json_encode() function returned a JSON that is not valid

In my PHP file (although more complex, even with the simplest code it fails), I have: <?php $salida = array(1,2,3,4,5); echo json_encode($salida); ?> The response received is: [1,2,3,4,5] While this appears valid, it's actually not. When pas ...

Converting Repository Objects to Json in Symfony3

element, I am facing an issue while attempting to send a repository object as JSON. In my controller code, I have implemented a conditional check to ensure that the request is made via XmlHttpRequest. Upon receiving the data and fetching the corresponding ...

Exploring the process of how Spring MVC's DeferredResult is transmitted back to an AngularJS client

Having little experience with Spring MVC and AngularJS, I am working on an application that synchronizes selected tables from two database instances. When the synchronization process is triggered, a specific service is called at the server end: @RequestMa ...

Understanding the method of interpreting an unfamiliar provider error within AngularJS

There is currently a console error that reads as follows: Error: [$injector:unpr] Unknown provider: userProvider <- user <- MainCtrl Based on my understanding from the AngularJS documentation at https://docs.angularjs.org/error/$injector/unpr, this ...

Absolute positioning causes an element's height to increase

As I delve into the realm of typographical animations and seek to calculate the baseline of a font at various sizes, I've stumbled upon a peculiar discovery: It appears that the height values of elements tend to increase in an erratic manner when thei ...

Transforming .POST into corresponding .AJAX techniques

I'm currently attempting to convert a .post javascript call into an equivalent .ajax call in order to make it asynchronous. However, I'm running into some issues and can't seem to get it to work. The original working .post call looks like th ...

Learn how to properly convert a string into a valid URL using the Next JS router when pushing pages

I'm dealing with a string that looks like this: /dashboard/products/:id. My goal is to utilize Next Js's router to navigate to that URL and replace the placeholder :id with an actual id. Here's the code I've written: {products.map(prod ...

Angular loop is unable to detect changes in the updated list

My Angular application is facing a peculiar issue that I can't seem to figure out. // Here are the class attributes causing trouble tenants: any[] = []; @Input() onTenantListChange: EventEmitter<Tenant[]>; ngOnInit(): void { this. ...

Remove item from jQuery's "raw text" HTML

Suppose I have the following JavaScript string: var string = '<div id="div1"><div id="div2"></div></div>'; Is it possible to utilize jQuery in order to create a new string as shown below? var newString = '<div i ...

Building a bespoke search input for the DataTables JQuery extension

As the title indicates, I am in the process of developing a custom search box for the DataTables JQuery plugin. The default options do not suit my needs, and configuring the DOM is also not ideal as I aim to integrate it within a table row for display purp ...

Tips for fading the text of list items when their checkbox is marked as done?

I am trying to figure out how to gray out a list item when its checkbox is checked. The code I currently have takes text input from a textbox and adds it to an unordered list when the add button is clicked. Each list item contains a checkbox within it. My ...

Refresh jQuery CSS for active button whenever a different button is clicked

I want to enhance a group of buttons using jQuery. I aim to make the active button visually stand out so that users can easily identify it. These buttons are being created through a PHP foreach loop, as shown below: foreach($result as $row){ echo "< ...

How to Stop Browser Tooltip from Displaying HTML Tags within "innerHtml" in Angular 6

In my Angular application, a template is using the following code snippet: ... <span [innerHtml]="textVar"></span> ... The textVar variable is created to allow for special styling on certain characters or strings. It's formatted using th ...

Animation not fluid with ReactCSSTransitionGroup

Currently, I am in the process of developing an image carousel that showcases images moving smoothly from right to left. However, despite its functionality, there seems to be a slight jaggedness in the animation that I can't seem to resolve. Interesti ...

The inner workings of v8's fast object storage method

After exploring the answer to whether v8 rehashes when an object grows, I am intrigued by how v8 manages to store "fast" objects. According to the response: Fast mode for property access is significantly faster, but it requires knowledge of the object&ap ...