A SpringBoot and Angular function that retrieves a numerical value

I need to retrieve the number of users from a table called Users and display it on the frontend using Angular. Below are my methods that return the number of users on the backend:

UserRepo.Java

@Query(value="SELECT COUNT(*) FROM User")
int getUsersCount();

UserController.Java

@GetMapping("/countUsers")
  @PreAuthorize("hasRole('ADMIN')")
    public int countUsers() {
      
     
      return  UserService.getUsersCount();

            
    }

The issue I am facing is that I am unable to retrieve the result as a number on the frontend, it always shows as undefined. Here is how I am calling my method on the frontend:

UserService.ts

 countUsers() {  
    return this.http.get(`${AppConstants.API_URL}`+'countUsers');     }

UserComp.ts

 public count(){
     this.userService.countUsers().subscribe(
     
     );

When I try to display the result with this.count(), it returns undefined. Additionally, when I attempt to change the return type to number in the service part, I get an error stating:

Type 'Observable' is not assignable to type 'number'

Answer №1

By default, the responseType for a GET request is set to 'json'. This means that the HttpClient will attempt to parse any data returned by the backend as JSON.

If the result of parsing the count as JSON returns undefined, you may want to try providing a second options parameter and setting the responseType to text instead:

CountUsers(): Observable<any> {  
  return this.http.get(`${AppConstants.API_URL}`+'countUsers', { responseType: 'text' });
}

To access the count result, subscribe to the observable like so:

public userCount?: number;

ngOnInit(): void {
  this.userService.CountUsers().subscribe((count) => {
    this.userCount = count;
    console.log(count);
  });
}

For more information, refer to the documentation.

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

When doctype is specified, `$(window).height()` will output the height of the document

Recently, I've encountered an issue where trying to retrieve the browser's window height using $(window).height() has been returning a significantly larger number, likely indicating the document height instead. It's strange because I've ...

Enhance the textarea using Javascript when clicked

I am experimenting with styling my textarea using a combination of JAVASCRIPT and CSS. The goal is to make it expand in size from 20px height to 120px height when clicked, using document.getElementById("tweet_area"). However, I am facing an issue where t ...

AngularJS allows you to dynamically disable a button based on a value in an array

I have an array containing letters from A to Z and I want to create a list of buttons using them. $scope.alphabet = "abcdefghijklmnopqrstuvwxyz".split(""); I also have another array: $scope.uniqChar = ['a', ' ...

What is the best way to combine two nearly identical arrays/objects using underscorejs or a similar library?

In the realm of lists, there exists an old list and a new one. The mission at hand is to combine both, even in the presence of newly added key-value pairs. var oldList = [{ id: 1, name: 'Michael', sex: 'male', goodlooking: 1 }, ...

Why are the height and width values I specified not matching the values returned?

I am currently learning HTML and JavaScript, specifically diving into the width() and height() methods in JavaScript. Setting the dimensions of div1 to 100px for height and 300px for width, I encountered a discrepancy when running the code. Upon execution ...

How can I restrict the selection of only one checkbox within an iframe window?

Here is my JavaScript snippet: var iframe = document.getElementById('pltc'); iframe.contentWindow.document.open('text/htmlreplace'); iframe.contentWindow.document.write('<input type="checkbox" name="tc0">Yes<input type="c ...

Splitting JavaScript Arrays: Exploring Efficient Division

I'm attempting to develop a recursive function that divides an array in half until it only consists of lengths of 3 and 2. After dividing, I want to neatly organize all the new arrays into another array. My idea is to find a way to determine the numb ...

Meteor's Minimongo does not seamlessly sync up with MongoDB

Despite following the tutorial for my Meteor application using Angular 2 and Typescript, I am facing difficulty loading server data on the client side. Whether autopublish is turned on or off, I have attempted numerous times to display data from different ...

Passing an object as a parameter using JavaScript's XMLHttpRequest

My data array is structured like this: var data = [ { 'name': 'Foo' }, { 'name': 'Bar' } ] I need to send it to my php script using pure Javascript without using jQuery. This is how ...

Click on the div to add items from an array into it

I have a unique set of lines stored in an array: var linesArr = ["abc", "def", "ghi"]; In my JavaScript, I dynamically create and style a div element using CSS: var div = document.createElement("div"); div.className = "storyArea"; div.in ...

Show a div element if the user is redirected to a certain page

Looking to display a div only when the page is accessed through a redirected URL. I am open to using either JavaScript or PHP, whichever is simpler. Here's the PHP code I attempted: <?php if (preg_match("/site.com/", $_SERVER['HTTP_REFERER&a ...

Steps to replicate the items in an array

Suppose we have an array : var array_1 = ['c','b','a']; What would be the most efficient method to convert array_1 into ['c','c','b','b','a','a']; or possibly [& ...

NestJS API experiencing issues connecting to MongoDB due to empty index keys

My goal is to create an API with NestJS using TypeORM. Initially, I had set up the API to work with Postgres, but now I need to migrate it to MongoDB. After making the necessary changes, the connection is established successfully. However, I encounter an ...

Signature in TypeScript for a function that augments the number of elements in a tuple

Can a type-aware declaration be written in Typescript for a function that takes a tuple and returns a new one with an appended item, without using function overload? In short, I need a function that performs the following: [T1, T2, ... Tn] + U => [T1 ...

What could be causing my header component to rerender even when there are no new props being received?

https://codesandbox.io/s/crimson-field-83hx6 In my project, I have a Header component that simply displays a fixed text and includes a console.log statement: const Header = props => { console.log("header render"); return ( <header> ...

Is there a universal method to transform the four array values into an array of objects using JavaScript?

Looking to insert data from four array values into an array of objects in JavaScript? // Necessary input columnHeaders=['deviceName','Expected','Actual','Lost'] machine=['machine 1','machine 2&apo ...

Designing Buttons and Titles for the Login Page

I'm currently working on developing a straightforward login page in react native and I've encountered some difficulties with styling. Does anyone have tips on how to center the text on the button? Also, is there a way to move the INSTARIDE text ...

Incorporating a TypeScript module into a JavaScript module within a React application

I'm encountering an issue with my React app that was created using create-react-app. I recently added a Typescript module to the project, which is necessary for functionality reasons. Although it will remain in Typescript, I made sure to install all t ...

What is the best way to integrate external JavaScript into a React application?

I've recently ventured into Reactjs and created a simple typing app using it. Interestingly, I transitioned this app from my previous PHP project. Now, I am looking to integrate my custom JavaScript file into the Reactjs app. The Home.js file look ...

Troubleshooting the Ineffective Replace Method in React Component

When working in my React component, I have implemented the use of the replace method to substitute a word. However, it seems that this functionality is not generating the expected outcome: const myComponent = () => { const [textVal, setTextVal] = ...