Deciphering the $resource factory along with the @ symbol prefix

Under this particular service:

vdgServices.factory('UserService', ['$resource',
function($resource) {

    return $resource('api/users/:id', {}, {

        doGet: {
            method: 'GET',
            params: { id: '@userId' }
        },

        doPost: {
            method: 'POST',
            params: { id: '@userId' }
        },

        doPut: {
            method: 'PUT',
            params: { id: '@userId' }
        },

        doDelete: {
            method: 'DELETE',
            params: { id: '@userId' }
        }

    });

}]);

I have noticed the different URLs being requested as follows:

var params = { userId: 42 };
var onSuccess = function() { console.log("OK"); };
var onError = function() { console.log("KO"); };

UserService.doGet(params, onSuccess, onError);
// requests api/users?userId=42

UserService.doPost(params, onSuccess, onError);
// requests api/users/42

UserService.doPut(params, onSuccess, onError);
// requests api/users/42

UserService.doDelete(params, onSuccess, onError);
// requests api/users?userId=42

Could someone clarify why the :id URL parameter is sometimes substituted with 42, and other times not?

Ideally, I would prefer it to be replaced consistently for all methods, resulting in the URL "api/users/42" every time.

Answer №1

Mastering AngularJS $resource

When using the "@" prefix for a parameter value, it will be populated from the corresponding key on the data object, which is especially useful for non-GET operations.

The correct way to implement params is shown below:

.factory('UserService', function($resource) {
    return $resource('api/users/:id', { id: '@id' }, {

        doGet: {
            method: 'GET'
        },

        doPost: {
            method: 'POST'
        },

        doPut: {
            method: 'PUT'
        },

        doDelete: {
            method: 'DELETE'
        }

    });
});

Let's Put It to the Test

describe('userApp', function () {
    var UserService
      , $httpBackend
    ;

    beforeEach(function () {
        module('userApp');
    });

    beforeEach(inject(function (_UserService_, _$httpBackend_) {
        UserService = _UserService_;
        $httpBackend = _$httpBackend_;
    }));

    describe('User resource - api/users', function () {
        it('Calls GET – api/users/{id}', function() {
            $httpBackend.expectGET('api/users/42').respond(200);

            UserService.doGet({id: 42});

            $httpBackend.flush();
        });

        it('Calls POST - api/users/{id}', function() {
            $httpBackend.expectPOST('api/users/42').respond(200);

            UserService.doPost({id: 42});

            $httpBackend.flush();
        });

        it('Calls PUT - api/users/{id}', function() {
            $httpBackend.expectPUT('api/users/42').respond(200);

            UserService.doPut({id: 42});

            $httpBackend.flush();
        });

        it('Calls DELETE - api/users/{id}', function() {
            $httpBackend.expectDELETE('api/users/42').respond(200);

            UserService.doDelete({id: 42});

            $httpBackend.flush();
        });
    });
});

Live demonstration available at: http://jsfiddle.net/krzysztof_safjanowski/vbAtL/

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 Vue allow for text selection to be encapsulated within a span element with two-way binding for styling

I have developed an application that allows users to highlight text with different colors while reading. For this functionality, I am utilizing the Selection API. However, I am encountering issues with the two-way binding aspect. When a user changes the c ...

Incorporating interactive elements and expanding rows within a multidimensional JSON array using AngularJS

I've got an array of JSon objects structured like this: var myObject= [ {"name":'Tom', "city":'Chicago',"GroupCode":'1'}, {"name":'Harry', "city":'Wisconsin',"GroupCode":'1'}, {"name":&apo ...

Does the require function in nodejs have any connection to the package.json file?

If 'random_module' is included in the list of dependencies in my package.json file, can I use the code var rm = require("random_module"); to access it? Essentially, does the argument for require function apply to any module listed under the depen ...

Menu changes when hovering

I want to create an effect where hovering over the .hoverarea class will toggle the visibility of .sociallink1, .sociallink2, and so on, with a drover effect. However, my code isn't working as expected. Additionally, an extra margin is automatically ...

Ways to transfer information among Angular's services and components?

Exploring the Real-Time Binding of Data Between Services and Components. Consider the scenario where isAuthenticated is a public variable within an Authentication service affecting a component's view. How can one subscribe to the changes in the isAut ...

Can you explain the distinction between $and and $all in this specific scenario?

These two lines of code may seem similar, but is there a crucial difference between them? I understand the importance of documentation, but in this specific scenario, what sets them apart? Thank you for your insights! db.someData.find({$and: [{genre: {$eq ...

Unlock the navigation tab content and smoothly glide through it in Bootstrap 4

Hey there, I have managed to create two functions that work as intended. While I have some understanding of programming, I lack a background in JavaScript or jQuery. The first function opens a specific tab in the navigation: <script> function homeTa ...

Creating a Javascript object from a JSON string

Looking for a way to convert a JSON string into a JavaScript object? You can make use of the following code snippet obtained from the server: JSON String: ["{"title":"Admin Dhaka","href":"#0","dataAttrs":[],"data":["{\"title\":\"BNS HAJI M ...

I possess a JSON array object and need to identify and extract the array objects that contain a specific child node

const jsonArray = { "squadName": "Super hero squad", "homeTown": "Metro City", "formed": 2016, "secretBase": "Super tower", "active": true, "members": [ { "name": "Molecule Man", "age": 29, "secretIdent ...

Is there a way to implement multiple "read more" and "read less" buttons on a single page?

I am currently working on a rather large project and I am encountering some issues with the read more buttons. As someone who is fairly new to JavaScript, I am still grappling with the concepts. While I have managed to make the function work for the first ...

What is causing the Unhandled Rejection (TypeError) error after I move the object in my Redux application and receive the message "Cannot read property 'filter' of undefined"?

I've been working on a Redux application. I've made modifications to a couple of files, and here are the changes in the two files: index.js: const store = createStore( reducer, { propReducer: { day: 1, data: [], filte ...

How to properly store response text in JavaScript variable?

Utilizing Ajax to execute a PHP script on my website, I aim to assign the response from the PHP script to a JS variable. The objective is for this script to set the variable "stopAt" to 42. This is where I encountered an issue: Below is the code snippet ...

Using Promise.all within the useEffect hook in ReactJS

I encountered a scenario where I needed to make two API calls one after another, with the second call dependent on the response from the first one. Fortunately, I managed to utilize the Promise.all function along with axios in my React project. However, I ...

Retrieve data from a URL using Angular 6's HTTP POST method

UPDATE: Replaced res.json(data) with res.send(data) I am currently working on a web application using Angular 6 and NodeJS. My goal is to download a file through an HTTP POST request. The process involves sending a request to the server by calling a func ...

Issues with sending parameters via an initialisation function in JavaScript

I am struggling with passing arguments to a new object when using an initializer function. Let's look at my examples where I aim to create an object that returns an array. Object Ex1 works as expected: Ex1 = function() { myVar = []; myVar = ...

I am wondering about automation protractor - What is the best way to select the first value in the "job no" column of the first row in a table?

https://i.sstatic.net/nMKyp.png I am presenting three table structures on a single page. Take a look at the screenshot to see how the page will appear. ...

javascript selecting window location strings

Hey there, http://localhost/estamo/asset.php?aname=VklQIFBsYXph&di=Ng== I have this URL and I want to retrieve it using Javascript: var locat = window.location.href; $.get("enviaramigo.php?email="+$("#email").val()+"&url="+locat, function(h ...

Toggle among 10 divs, but automatically revert back to the initial div if there is no mouse activity for a short period

My website has 9 links in the header and 10 divs in the body. The first div serves as the main page, while the remaining 9 divs contain different content. I would like to implement a feature where when users hover over the 9 links, it displays one of the 9 ...

Implementing an onclick function to execute a search operation

Utilizing PHP, I am dynamically populating a dropdown submenu with rows from a database. If the user wishes to edit a specific record listed in the menu, I want to enable them to do so without requiring any additional clicks. My goal is to accomplish this ...

Automatically refresh the div as soon as a new entry is added to the database

I am attempting to extract all the data rows from a table that existed before the user visited the page and then update the div with any new rows of data that have been added to the table since the user's visit (similar to how WhatsApp displays conver ...