What is the best way to implement restful instead of query syntax in a $resource factory?

Recently, I set up a $resource factory like this:

(function() {
    'use strict';
    app.factory('WidgetFactory', [ '$resource', function($resource) {
        return $resource('http://localhost:8282/widget/:widgetId', { widgetId : '@id'},{
                rate: {method:'POST', params:{applyRating:true}}
            });
    }]);
}());

Now, in my controller, I'm trying to retrieve the widget with id 1:

this._widgets = WidgetFactory.get({ id:1 }); // or WidgetFactory.query({ id:1 })

However, the request is sent as

http://localhost:8282/widget?id=1
, when it should be widget/1.

How can I adjust the request in the $resource from the controller to generate widget/1? Essentially, how do I utilize the '@id' parameter within my resource factory (what is the actual functionality of '@id')?

Answer №1

To ensure proper functionality, it is advisable to match the paramDefault key/value pairs as explained in detail in a recent discussion on angularjs $resource not replacing variable in url template for POST

For instance, if your $resource configuration resembles the following:

app.factory('WidgetFactory', [ '$resource', function($resource) {
    return $resource('http://localhost:8282/widget/:widgetId', { widgetId : '@widgetId'},{
            rate: {method:'POST', params:{applyRating:true}}
        });
}]);

Your controller call should be structured like this:

this._widgets = WidgetFactory.get({ widgetId:1 });

Check out the Demo

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

Can you guide me on integrating an Angular 2 page into a Spring MVC Application?

I am looking to integrate index.html from an angular 2 project as the welcome page for a Spring MVC application. When running the angular 2 project with 'npm start', the components load correctly. However, without running 'npm start', t ...

What is the best method to collect information from multiple AJAX requests?

In addition to synchronous AJAX calls, what is the most effective approach for handling a situation like this? var A = getDataFromServerWithAJAXCall(whatever); var B = getDataFromServerWithAJAXCallThatDependsOnPreviousData(A); var C = getMoreDataFromServe ...

What is the best way to continue looping until my variable matches the user's input? JavaScript

As of now, this nested for loop continues until both i and j reach 3. How can I reset the variables once they have reached their maximum value so that the loop can continue running? Alternatively, is my current approach incorrect? for (i=1; i<=3; i=i+ ...

Direct your attention to alternative data sources following the selection of an item in the typeahead search feature

Having some trouble with angular-ui bootstrap: I am using 2 input elements: <input type="text" ng-model="selected" uib-typeahead="state for state in states | filter:$viewValue | limitTo:8" typeahead-on-select="focusSuccessive($item, $model, $label, $ev ...

Transitioning menus in Ionic 2

I followed the instructions in the Ionic 2 menu documentation and tried to display the menu in a specific way: https://i.sstatic.net/zzm8f.png My intention was to have the menu displayed below the content page while keeping the menu button visible. Howe ...

The storage format of the input field is handled differently on the angularjs controller side

Check out the plunker link for this directive in action. A comma is automatically added as the user types in the input, and it displays numbers with 2 decimal places. However, there seems to be an issue where entering '2300.34' results in ' ...

What Causes the "Not a String or Buffer Type" Unhandled Exception?

I've encountered an error that seems to be originating from the following line of code, even though I believe I am following the example correctly (viewable at https://www.npmjs.org/package/aws-sign). Any help or hints would be greatly appreciated. v ...

Is there a way to modify page URLs without causing a refresh, regardless of browser?

Despite my extensive searches on various online platforms, including stackoverflow, I have yet to come across a satisfactory answer to my question. While I find the window.history.pushState() and window.history.replaceState() methods quite user-friendly, ...

Display overlay objects specifically focused around the mouse cursor, regardless of its position on the screen

I am currently working on a project using SVG files and processing.js to develop a unique homepage that incorporates both animation and static elements. The concept is to maintain the overall structure of the original homepage but with varying colors, esse ...

Tips for successfully passing a ViewBag in ng-click

<th><a href="javascript:;" ng-click="order(@ViewBag.desc)">Name</a></th> I am currently implementing this code and trying to fetch data from the view bag into my Angular Controller. However, I seem to be facing some challenges in a ...

Unable to access setRowData() in AgGrid/Angular 2 leads to rendering of the grid without displaying any rowData

Resolved I think my solution is temporarily fixed and it reveals that I may have set up my mongoose model incorrectly. The answer provided did assist me in solving my issue, but ultimately the reason for the empty data rows was due to incorrect identifier ...

Encountering a login issue with the jsonwebtoken code, specifically getting the error message "something went wrong logging in TypeError: Cannot read properties of undefined (reading 'sign')."

I encountered an error in my console saying, "something went wrong logging in TypeError: Cannot read properties of undefined (reading 'sign')." I am seeking assistance in resolving this issue. Below is the code snippet: import { mAdmin } from &q ...

What is the best way to reset the state in React prior to the render being called?

Whenever I click on a copy icon, a popup is displayed. This happens because the state "showPopup" is set to true upon clicking the copy icon, and the render function recognizes this and shows the popup. The popup will close automatically if I click anywher ...

when successful, refresh the page

I am currently utilizing the following javascript code to load recrefresh.php when the page first loads. Upon executing the ajaxvote function, I aim for the subsequent div to be refreshed: <div class="recrefresh"></div> After attempting to ad ...

Utilize JavaScript to create a toggle menu feature that can target multiple variables with just one click function

I am attempting to create a collapsing menu on click functionality with additional modifications. One of the changes I would like to implement is altering the background of another element when the menu collapses. Currently, the code snippet only works fo ...

Restriction on Google Maps API: Mouseover functionality is limited to specific hours of the day

Throughout my programming journey, I've encountered some weird errors, but this one takes the cake. I'm stumped as to why it's happening. Here's the situation: My application is supposed to fetch data from a MySQL Database and display ...

Error message found: "Uncaught TypeError: e[n] is undefined while setting up redux store in a reactjs application

Delving into the world of Redux for the first time, I decided to tackle the Todo List example from the official redux.js.org website. After testing the code, everything seemed to be working fine with the redux store initialized only with the reducer as a p ...

Utilizing Jest to Mock a jQuery Method within a Promise

I have created a function that utilizes a jQuery function named dataFunc, which is expected to return an object. Instead of testing the dataFunc function itself, I want to focus on testing the promise it produces. To achieve this, I need to mock the respo ...

Click on the ng-click attribute to access the HTML page

I need a button that can perform the following tasks: Execute multiple functions from the controller using ng-click(they must be called in HTML) Direct to another html page located in "static/page.html" onclick, when used for navigation (location.hr ...

What are the best practices for ensuring secure PUT and DELETE requests?

For the backend of my current project, I have a question regarding security measures. As an illustration, one of the tasks involves handling various "/notes" requests. /notes => retrieve all notes belonging to the authenticated user /notes => creat ...