Creating a personalized instance function in Angular's $resource

When working with AngularJS, all actions for a $resource are added as $customAction methods to the Resource. This allows me to easily invoke them as methods on resource instances. For example:

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

In this case, $save is the equivalent of the save action and can be called directly on the user instance.

Now, if I introduce a custom action like the following, it will create a $attributes method on every instance of the user:

var User = $resource('/user/:userId', {userId:'@id'}, {
  attributes: { method: 'GET', url: '/user/:userId/attributes', isArray: true }
});

However, when attempting to use this newly defined method, an error occurs stating

Object #<Resource> has no method 'push'
:

User.get({userId:123}, function(user) {
  var attrs = user.$attributes();    // error
  // ...
});

Could it be that I misunderstood the concept of custom actions?

Answer №1

Consider utilizing parameters instead of relying solely on the URL path

var User = $resource('/user/:userId/:customAction', {userId:'@id'}, {
  attributes: { method: 'GET', params: { userId:'@id', customAction: 'attributes'}, isArray: true }
});

Answer №2

After trying different approaches, I found my ultimate solution by transitioning to a library called Restangular. This library allows for nested resources through a chaining syntax, enabling me to easily perform actions like the following:


Restangular.one("user", 123).all("attributes").get()

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

"Exploring the power of Angular's translation capabilities paired with

I'm currently working on translating a multistep form using Angular Translate and routing with ui-router. Everything seems to be functioning properly except for one issue. Below is the snippet of my code: Translation Setup: .config(function ($t ...

Retrieving Information from an API with Custom Headers in React Native

I have an API that necessitates specific headers for access. Without these headers, a browser displays the following error: Code: 4101 Message: Header X-Candy-Platform is required However, when the headers are provided, the API returns a json response. ...

Adding hue to the portion of text following a JavaScript split() operation

I need assistance in printing the text entered in a textarea with different colors. I am separating the string using the split() method, which works fine. However, I now want to print the substrings in the textarea with colors. How can this be achieved? & ...

Breaking auto-update functionality when using the 'dd-slick' jQuery plugin to style chained drop-downs

Utilizing the jquery.ddslick.min.js plugin from jQuery for creating customized drop-down menus with image options. Additionally, incorporating the jquery.chained.min.js script to automatically update the content in the second select box based on the select ...

Packages and Digital Routes

Currently in the process of creating a new website utilizing angular, MVC, and Web API. The plan is to keep the static content (js, css, images, etc) in Site A, the MVC site in Site B, and the api in Site C. These will be separate sites, not virtual direct ...

Creating a Dynamic Canvas Rendered to Fit Image Dimensions

I'm struggling with a piece of code that creates an SVG and then displays it on a canvas. Here is the Jsbin Link for reference: https://jsbin.com/lehajubihu/1/edit?html,output <!DOCTYPE html> <html> <head> <meta charset=&qu ...

Angular 2: Despite changes in property, ElementRef.nativeElement.offSetwidth consistently returns the same value

Recently, I encountered an HTML element that caught my attention: <h1 [style.font-size.em]="mysize" id="title-text" #titleText>{{ screenInfo.title }}</h1> This particular element piqued my curiosity because the variable "mysize" controls the ...

Using TypeScript to sort objects based on keys and convert an array of objects into a different object type

I'm facing an issue where I need to filter the objects within an array of objects based on keys and convert them into a different type of object. I attempted to solve it like this... const values = Object.keys(user).map((key) => {'refKey' ...

Having issues with clicking on a row in the table while using AJAX functionality

Experiencing a puzzling issue while attempting to add click functionality to table rows with AJAX, here is the JavaScript code used: //for tabs $(document).ready(function () { $("#tabs").tabs(); }); $(window).load(function() { jsf.ajax.addOnEven ...

How can we ensure that an enum is accessible throughout the entire meanjs stack?

Currently, I am exploring the meanjs technology stack and facing a challenge in creating a centralized enum array that can be accessed throughout the project, from MongoDB to Angular. Can anyone suggest a smart solution for accomplishing this task? ...

Tips for creating an HTML page with the dimensions of an A4 paper sheet?

My goal is to display the HTML page in a browser while containing the content within the dimensions of an A4 size page. Additionally, when printed, the HTML page should be formatted to fit onto A4-sized paper pages. <div classNa ...

The mouseup event fails to trigger upon dropping a component with React-dnd

Currently, I am working on a project that requires drag and drop functionality using the React-dnd package. While I have been able to successfully implement this feature, I am facing an issue with the target component where draggable items are supposed to ...

Adjusting the shadow on the inserted image

Currently, I am using fabric.js to manipulate images that are added to my canvas. The issue I am facing is with the shadow around the image not being even. The code I have tried so far is displayed below, but you can view what I am aiming for by clicking h ...

Utilizing the power of Material-UI with React in conjunction with Python-Django: A comprehensive

I am seeking guidance on implementing React with Material UI components in my web application. The technologies I have utilized in multiple projects include: Materialize CSS, Javascript, Jquery. The technologies I wish to explore for future projects are ...

Establishing a small boutique utilizing Vue.observable for property getters

I am currently importing the createStore function into a store.js file and passing an object with state properties and mutation functions as an argument, which is working well. createStore.js import Vue from 'vue' function createStore({ state, ...

Which medium is the optimal choice for file manipulation in Node.js and JavaScript?

Is there a simple way for JavaScript to receive incoming data from Node.js that was obtained from an external server? I've been searching for a solution to this problem for days now. Here's my current approach: I plan to have both the server-sid ...

Unexpected outcomes arise when parsing headers from a file-based stream

Currently, I am in the process of creating a small parser to analyze some log files using node streams (more specifically io.js). I have been referring to the documentation for unshift to extract the header. While I can successfully divide the buffer and ...

Troubleshooting issues with Firebase integration in a Node.js environment

I am currently encountering difficulties implementing Firebase in my Node.js project. Below is the code snippet that I am attempting to execute on Node. var firebase = require("firebase"); var admin = require("firebase-admin"); var serviceAccount = requi ...

Create a new function within the GraphQL Resolvers file

I am trying to define a function within the same ts file as where I specify the resolvers export const resolvers = { Query: { books: () => { return [ { title: 'Harry Potter and the Chambe ...

Enhancing Grails dynamic dropdown to include a pre-selected value in edit.gsp

One feature I have implemented is a dynamic dropdown menu in my _form.gsp file that appears in both the create and edit pages. While it currently works as intended, I am seeking a way to display the selected value on the edit page. _form.gsp <g:s ...