Receiving a commitment from an Angular Resource

When working with $resource in Angular for CRUD operations, I'm encountering some confusion regarding the usage of different resource methods.

From what I've observed, the "regular" methods like save() and get() appear to execute synchronously. If you need asynchronous behavior, you can provide a callback function to run upon completion. Additionally, each method's result includes a $promise property that returns a promise, enabling asynchronous handling (which is my preferred approach).

However, there also exist $ versions of these methods, except for get() and query(). I am puzzled by the absence of $get() or $query() and wonder if these $ methods serve as shortcuts for .$promise.

Answer №1

It's quite a challenge to grasp the documentation for ngResource. Essentially, you must distinguish between

  • class actions (methods of $resource) and
  • instance actions (methods of instances of $resource)

For example, class actions like

var User = $resource('/user/:userId', {userId:'@id'});
User.get({userId:123}, function(user) {
  user.abc = true;
  user.$save();
});

come with an added property $promise that is resolved upon receiving data from the $http request. This is why it can be expressed as:

User.get({userId:123})
    .$promise.then(function(user) {
      $scope.user = user;
    });

as mentioned in the docs:

Once the server responds with data, the object becomes an instance of the resource class. Actions such as save, remove, and delete are accessible as methods with the $ prefix. This simplifies performing CRUD operations (create, read, update, delete) on server-side data like so:

This explains why user.$save(); can be triggered on the instance in the aforementioned example.

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

I'm unsure how to utilize the generic type in this particular scenario. It's a bit confusing to me

Recently, I delved into TypeScript generics and applied them in specific scenarios. However, I encountered some challenges. While working with two different interfaces, I faced a need for flexibility. For instance, I needed to make server requests. func ...

Locating the exact position of a DOM node within the source document

Purpose In the process of creating a series of 'extractor' functions to identify components on a page using jsdom and nodejs, I aim to organize these identified 'component' objects based on their original placement within the page. Ch ...

I am interested in developing a JavaScript program that can calculate multiples of 0.10

I am looking to let users input values that are multiples of 0.10, such as - 0.10, 0.20, 0.30....1.00, 1.10, 1.20...1.90, and so on. When a user enters a value in the text box, I have been checking the following validation: amount % 0.10 == 0 Is this a ...

"Retrieve the position of a contenteditable element while also considering HTML

I've been exploring a method to generate annotations within HTML text using JavaScript. The approach involves the user clicking on a contenteditable <div> and obtaining the cursor's position based on their click. Subsequently, when insertin ...

Scripting events in JavaScript/jQuery are failing to trigger on elements located inside nested <div> containers

I am currently developing a simple RSS reader application where, upon clicking a 'story', the relevant information is displayed in a modal view. The 'stories' or RSS feed items are presented in a scrolling row. However, I have encounte ...

Getting just the main nodes from Firebase using Angularfire

I'm having trouble figuring out how to print just the parent element names from the structure of my database. The image provided shows the layout, but I can't seem to isolate the parent elements successfully. ...

Guide on retrieving the response headers with jQuery and AJAX

Connection: keep-alive Content-Length: 2231 Content-Type: text/html; charset=utf-8 Date: Thu, 13 Sep 2018 07:37:46 GMT ETag: W/"8b7-XOXhf04O/VM7yxWQ561PEgxRfz8" x-auth: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJfaWQiOiI1YjlhMGEyM2Q0NmI3YjFmYTQzNWI ...

Error arising from attempting to compile React animations for a specific component, rc

As someone new to React, I decided to try running a sample example from the following link: To do this, I created a file named MonApp.js with the code snippet below: import React, { Component } from 'react'; import { render } from "react-dom"; ...

Encountered an error trying to access the length property of an undefined variable while passing props

I need help with my shopping app project. I am trying to create a feature where if the cart is empty, it should display a message saying "shopping cart is empty." However, when I try to implement this, I keep getting a type error that says "Cannot read p ...

Suggestions for improving the smoothness of the Bootstrap toggle hide/show feature

Recently completed my bootstrap toggle hide/show feature and everything seems to be functioning correctly, except for the transition between the different contents. The borders appear jagged and not smooth when activating the toggle. I suspect there may b ...

An issue with the JSON format encountered in the D3 pack layout

I am completely new to d3 and have only been learning it for the past 3 days. I attempted to create a pack layout, but I encountered an issue where I couldn't call the translate (or transform) function based on the data in an external json file. The s ...

Even after dynamically removing the class from the element, the Click event can still be detected

My buttons have a design like this: <a class="h-modal-btn branch-modal-btn"> Buy Now </a> The issue arises when I need to remove certain classes and add attributes to these buttons based on the query string in the URL. Skipping ahead ...

Unlocking the secrets of obtaining post values using Body-parser in your Express Node.js application

Currently, I am utilizing Express version 4.11.1 and Body-parser version 1.11.0 in my project. However, upon running the code snippet below, I encountered the following output: I am seeking suggestions on how to retrieve the form value. Output {} serve ...

Utilizing service-based global objects in Angular applications

Upon entry into my application, the GlobalApplicationController initializes several services that are utilized throughout the entire application, such as subscribing to sockets. It would be quite beneficial to have a CurrentUser object available - however, ...

Utilizing a function argument within the :not() selector

I am currently working towards the objective of selecting all elements in my document except for those within a specific class. This is what I have come up with so far: var x = document.querySelectorAll(":not(.myParameter)"); My aim is to make 'myPa ...

Error encountered: The use of 'import' and 'export' is limited to 'sourceType: module' when attempting to install Tweakpane

I am currently learning JavaScript and have been following a course on Domestika that requires me to install the Tweakpane package. I usually use Git Bash for installing packages, and I have successfully installed others this way before. Here is the proces ...

The ng-click event in AngularJS does not function as expected when nested within another ng-repeat loop

I am facing an issue with ng-click in my Angular application (version 1.0.4). The first ng-click works fine, but the second one does not. <div class="menu-group" ng-repeat="module in modules"> <div ng-click="toggle($event, $parent)" ...

extracting values from deeply nested JSON array in JavaScript

Is there a way to extract values from a deeply nested JSON array? I'm looking to retrieve all pairs of (nameValue and value) from the JSON provided below var json = [{ name: 'Firstgroup', elements: [{ ...

Adjusting the size of an element in Angular JS as a textarea expands

I have created a directive that allows for writing and previewing comments, similar to the conversations in Github. The directive consists of two HTML elements: a textarea and a div (utilizing angular-marked). My goal is to dynamically resize the div as I ...

The functionality of the AngularJS UI-Router seems to be impaired following the minification of

Hey there, I just developed an app with Angular and implemented ui-router for routing. To reduce the file size, I minified the entire Angular app using gulp-uglify. However, after minifying the app, the child route (nested route) of ui-router is no longer ...