How is it possible that both of my AngularJS services are being directed to the exact same Restful Java EE web service?

I am facing an issue with my two angularjs services. One is supposed to retrieve a single user while the other should return an array of users. However, both seem to be calling the service that returns an array of users. Can you help me understand why this is happening?

Below are the definitions of the two angularjs services:

angular.module('clearsoftDemoApp').factory('UserDetail', function ($resource) {
return $resource('http://localhost:8080/ClearsoftDemoBackend/webresources/clearsoft.demo.users/:id', {}, {
    find: {method: 'GET', params: {id: '@id'}},
    update: { method: 'PUT', params: {id: '@id'} },
    delete: { method: 'DELETE', params: {id: '@id'} }
});

});

angular.module('clearsoftDemoApp').factory('Users', function ($resource) {
return $resource('http://localhost:8080/ClearsoftDemoBackend/webresources/clearsoft.demo.users', {}, {
    findAll: {method: 'GET', isArray: true}
});

});

Additionally, here is a snippet of the Java RESTful service code:

@Stateless
@Path("clearsoft.demo.users")
public class UsersFacadeREST extends AbstractFacade<Users> {
@PersistenceContext(unitName = "ClearsoftDemoBackendPU")
private EntityManager em;

public UsersFacadeREST() {
    super(Users.class);
}

@GET
@Path("{id}")
@Produces({"application/xml", "application/json"})
public Users find(@PathParam("id") Integer id) {
    return super.find(id);
}

@GET
@Override
@Produces({"application/xml", "application/json"})
public List<Users> findAll() {
    return super.findAll();
}

The issue I am facing is that both angularjs services are unintentionally calling the findAll() web service instead of the intended ones. Any insights on resolving this would be greatly appreciated.

Answer №1

$resource is designed to fetch data from a designated endpoint, modify it as needed, and send it back. It comes with default parameters that can be overridden when making calls. Instead of explicitly defining resource functions, utilize AngularJS's internal resource matching process. For example, by only defining the UserDetails resource and calling

http://localhost:8080/ClearsoftDemoBackend/webresources/clearsoft.demo.users
, you will retrieve all users.

To achieve this, remember to specify :id as an optional parameter.

Additionally, make sure to include the [ngResource] module in your codebase.

var service = angular.module("clearsoftDemoApp", ["ngResource"]);
// UserDetail Resource
service.factory('UserDetail', function ($resource) {
  return $resource(
    '/ClearsoftDemoBackend/webresources/clearsoft.demo.users/:id',
    {id: "@id" }, 
    {
      find: {method: 'GET'},
      update: { method: 'PUT'},
      delete: { method: 'DELETE'}
  });
});

The following code snippet defines a UserDetail module that allows you to make the following API calls:

// Get all users
var users = UserDetail.query(); // Makes GET request to /ClearsoftDemoBackend/webresources/clearsoft.demo.users

// Get user with ID 1
var user = UserDetail.get({},{'id': 1}); // Makes GET request to /ClearsoftDemoBackend/webresources/clearsoft.demo.users/1

// Find user with ID 1
var user = UserDetail.find({},{'id': 1}); // Makes GET request to /ClearsoftDemoBackend/webresources/clearsoft.demo.users/1

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

Ways to add a line break within JavaScript code

I am currently developing a bot for my Discord server and working on logging messages to a text file. All the necessary information about the message is stored in a variable named logger, and I am using Node.js to append my log file. When attempting to ad ...

When a named capture group is included in the regex of a GET path, Express crashes with the error message: "Cannot read property 'name' of undefined at Layer

I am looking to process a GET request and extract specific information from the URL. Let's consider this scenario: const REGEX_QUERY = /^\/?house\/(?<street>[a-z]+)\/(?<house>[0-9]+)$/i; const REGEX_QUERY_NO_NAMES = /^\ ...

Breaking down the text field into two distinct fields

I have successfully modified the code below to meet a new requirement. The current functionality involves splitting the Price field into Pounds and Pence based on the index of the . symbol. However, I now need to extend this functionality to split a Name ...

Can two controllers be used for the main-app and sub-app with the same URL using angular ui-route?

I have implemented two controllers, 'BaseController' and 'SubController', for my main application and sub-application. Both controllers are configured to point to an empty URL. Below is the configuration for the main application:- ang ...

The dialogue within the map function is not functioning properly

In my state, I have saved data (objects) known as workitems. When these objects are mapped out to a table, everything functions correctly. However, upon trying to implement a Dialog feature with a button that allows users to view more information about a s ...

Utilize MongoDB and Mongoose to efficiently delete data using the findByIdAndRemove() method and redirect users accordingly

Currently, I am facing an issue with the DELETE method as the res.redirect doesn't seem to be working. The code in question involves trying to remove a record from MongoDB using findByIdAndRemove(): app.delete("/car", (req, res) => { Car.fi ...

Struggling to Convert LocalDate to Date in Java

I'm encountering an issue while attempting to convert LocalDate to date in my Java code. The error message I keep receiving is: {code: "unknown.unexpected", detail: "Text '02/28/1936' could not be parsed at index 0", meta: null} Below is ...

Counting words with JavaScript without using an input tag is a useful skill

Is there a way to count the words in a text using only p and span tags, without using input tags? How can this be achieved? <span class="word" id="word">Words Number</span> <p class="any" id="any"> ...

Revolutionizing messaging with Vue JS and Firebase

My web application is designed to check if a user has messages in the Firebase database. If messages are found, it retrieves the data from the users who sent those messages from my local database and displays them in a list using a v-for loop. The display ...

Changing the state using setState outside of the component does not trigger an update

My shop is situated within the store.js file like all the other Zustand stores: const retryStore = create(set => ({ retry_n: 0, setGRetry: (retry_n) => set(state => ({ ...state, retry_n, })), })); export { retryStore }; ...

Tips for adding a new value to an array of objects in React

As I navigate my way through the world of React as a newcomer, I've encountered a challenge that I need some advice on. I am attempting to add a new key and value to an array of objects, but I'm struggling to accomplish this task. Can anyone prov ...

Ways to modify the text of an HTML element when hovering over it

One of my elements contains the text &times; within a <span>. Is there a way to change this symbol to something else, like &infin;, when hovered over? <span class="change-text">&times;</span> When the mouse hovers over it, I ...

Having difficulties while setting up end-to-end testing using AngularJS scenarios and redis

I've hit a roadblock while trying to implement e2e tests in my Django app using angular-scenario. I want to create fake user login functionality for testing, but I'm struggling with getting it to work. Here's the test code I have: describe( ...

Exploring the functionality of ngTemplateOutlet, the implementation of @ContentChild, and the benefits of using ng

Lately, I've been dedicating more time to grasp the concepts presented in the blog post titled Creating Reusable Components with NgTemplateOutlet in Angular If you want to see the code in action, it's available on stackblitz. Within the UsageEx ...

Focus issue with MUI Custom Text Field when state changes

Currently, I've integrated the MUI library into my React Js application. In this project, I'm utilizing the controlled Text Field component to establish a basic search user interface. However, an unexpected issue has surfaced. Following a chang ...

A more effective method for restricting the properties of a field in an aggregate query

In my MongoDB query, I am attempting to use the aggregate function to fetch data from one collection while limiting the amount of data retrieved from another collection. Here is the code snippet that I have come up with: getFamilyStats: function (req, res ...

Having Trouble with window.location in Chrome Browser

In my code, there is a JavaScript function that utilizes window.location. Surprisingly, it runs smoothly in Firefox and Internet Explorer, but encounters issues while running on Chrome. I have tried testing it on both Ubuntu Hardy and Windows Vista opera ...

I am attempting to access an Angular variable using JavaScript, but unfortunately, I am encountering some issues

I'm currently implementing the following code: window.onload=function(){ var dom_el2 = document.querySelector('[ng-controller="myCtrl"]'); var ng_el2 = angular.element(dom_el2); var ng_el_scope2 = ng_el2.scope(); console.log ...

Having trouble setting the focus on a text box following a custom popup

Presenting a stylish message box and attempting to focus on a textbox afterward, however, it's not functioning as expected. Below is the HTML code: <a class="fancyTrigger" href="#TheFancybox"></a> <hr> <div id="TheFancybox">& ...

Is there a way to make three imageViews fill the entire width of a device using a GridLayoutManager?

Could someone please help me with adjusting the images to fill the entire width of the device screen? Right now there are noticeable white gaps between the images. Any advice on how to fix this? ...