Using Angular $resources in the query() function often results in the error message "Undefined is not a function

When I try to call the query() function using ngResource, I keep getting an error message saying "Undefined is not a function."

[demo.js]

var app = angular.module('StarterApp', ['ngResource']);

app.factory("resourceFactory", function($resource) {
  return $resource("js/demo2.json", {}, {
    'get':{method:'GET'},
    'query':{method:'GET',isArray:true,url:"js/demo2.json"},
    'save':{method:'POST'}
  });
});

app.controller('appCtrl', function($scope, resourceFactory){
  'use strict';

  var ajax = new resourceFactory;
  ajax.$query(function(response) {
    console.log(response);
  });

});

[demo2.json]

[
  {"demo2":"test"}
]

[error]

TypeError: undefined is not a function
    at http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular-resource.min.js:9:466
    at s (http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js:7:302)
    at d.module.provider.$get.e.(anonymous function).q.then.p.$resolved (http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular-resource.min.js:9:423)
    at http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js:112:20
    at l.$get.l.$eval (http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js:125:305)
    at l.$get.l.$digest (http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js:122:398)
    at l.$get.l.$apply (http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js:126:58)
    at l (http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js:81:171)
    at S (http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js:85:301)
    at XMLHttpRequest.D.onload (http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js:86:315)

When I use "$get" with a simple object return, everything works fine. I'm confused about what could be wrong with my code.

Answer №1

Opt for resourceFactory.query over resourceFactory.$query and avoid using the new keyword to create an object instance.

Code Snippet

resourceFactory.query(function(response) {
   console.log(response);
});

Answer №2

One possible reason for this error is attempting to make a promise on an Array.

When facing a similar problem, I enclosed the WebService array within a JSON object:

{ list: myArray })

Instead of simply using:

myArray

Implementing this change resolved the issue efficiently!

Using the same version of angularJS, it appears that the undefined error stems from the push methods.

More details about this problem can be found on GitHub in Issue 56, which remains unresolved.

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

Issue with AngularJS: Not able to get second app in template to function properly

I have encountered a puzzling issue with my two nearly identical apps. The first one seems to be running smoothly as expected, while the second one doesn't appear to be executing at all. Here is my code (jsfiddle): <div ng-app="passwdtool" ng-con ...

AngularJS: Issue encountered when trying to access isolated JavaScript file

If you have any recommendations or assistance, it would be greatly appreciated. //This piece of code represents my HTML content <!DOCTYPE html> <html> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"&g ...

Is it possible to retrieve the var name from an interpolated expression using template literals?

Suppose I have a variable like this: myVar = `Some text with ${eggs} and ${noodles} or ${pies}`; Is there a method to obtain myVar as an unprocessed string prior to variable substitution, essentially "Some text with ${eggs} and ${noodles} or ${pies}"? M ...

Retrieve the name of the file from a given URL by using JavaScript/jQuery, even when only the directory path is

I need to extract the current filename from the URL using: $currentFile = window.location.pathname.split("/").pop(); This method functions properly when the full path looks like: http://www.yoursite.com/folder/index.php It will return index.php, index. ...

Aggregating and organizing all TypeScript files within the project while preserving the file hierarchy

Looking to utilize a task runner such as Grunt or Gulp to compile TS to JS files in various locations within the project folder. The goal is to ensure that the outputted JS files are placed in the same directory where the project will look for them alongsi ...

THREE.js - Transformative Vertex Shader for Billboards

I am trying to figure out how to make an instance of THREE.Mesh always face the camera using a vertex shader instead of just relying on the [THREE.Mesh].lookAt() method. After reading through NeHe's Billboarding tutorial, I understand the concept exc ...

Embed three.js within a div container in an HTML document

I've been attempting to place the Canvas Lines three.js inside another div, but it doesn't seem to be working as expected. Instead, when I try, the JS code places the canvas at the very end of the body. Can anyone tell me why this is happening? ...

Having difficulty updating the parent for all PortfolioItem/Feature that were copied for a specific PortfolioItem/MMF

I'm facing a challenge in setting the parent for multiple features that I've copied for a specific MMF. However, only the parent of the last feature is being set. Below is the code snippet responsible for setting the parent: Record represents th ...

Please provide both an image and text in addition to a progress bar by using the form to

I am working on a form that needs to store both images and text data in a database. <form action="processupload.php" method="post" enctype="multipart/form-data" id="UploadForm"> <input name="name" type="text" /> <input name="age" ty ...

Is it possible to filter an array of data using a dropdown in Angular without using a pipe?

I am facing an issue with filtering data based on the selected dropdown item. Currently, it only filters the data once when I select a filter, and after that, it always returns an empty result. Here is an example of the code: <select class="select" (c ...

What is causing this code to break when using ajax's `data` parameter?

I'm relatively new to JavaScript, and I've been working on some code that seems to be properly formatted. However, whenever I add the data elements, it breaks the code. I've checked the jQuery documentation and as far as I can tell, I'm ...

Implementing real-time streaming communication between server and client with Node.js Express

When a post request is made, the server generates data every few seconds, ranging from 1000 to 10000 entries. Currently, I am saving this data into a CSV file using createWriteStream and it works well. How can I pass this real-time (Name and Age) data to t ...

Is there a way to integrate a calendar feature within an Angular 2 application?

I am brand new to Angular 2 and have a question: I need to integrate a calendar into a page where users can add events. Something similar to the following example: I'm unsure if the angular material calendar project is designed for Angular 2 or for ...

What alternative methods are available to rename a field that has been returned in mongoose, if at all possible?

I need help with this specific query: MessageModel.find({ conversationId: { $in: ids } }) .sort({createdAt: 'ascending'}) .populate({ path: 'receiver', select: '_id' }) .populate({ path: &a ...

Personalized ES6 Bootstrap module created for a toggle switch button in Vue

Utilizing the custom switch toggle in a Vue application is my current task. Check out this link for more on the custom switch toggle I found a button that suits my needs, but I am unsure how to properly integrate it into my component so it can handle the ...

What is the process for testing and executing the code I've written on ACE Cloud 9?

I have integrated ACE on my website to enable users to code freely. My question is, how can I execute the Python code they write? I want to add a run button in the bottom left corner (which I can style using CSS), but I'm not sure how to actually run ...

AngularJS - Triggering functions on image load event

I have been on a quest to find the best way to handle the onload event for images in Angular using jqLite. I came across this question, but I am looking for a solution that involves directives. Therefore, the approach below is not satisfactory to me: .c ...

What is the most effective way to populate an element using jQuery?

When you click a button with jQuery, I am generating a modal (Bootstrap modal) as a string. This modal has two option classes: Call Today and Call Tomorrow, which seems fine so far. Upon clicking the button, the modal is created, prompting me to add two a ...

Utilizing object properties to dynamically update components in VueJS

Are you familiar with dynamically changing a component using object props? App.vue <template> <div id="app"> <component :is="current['test'].target.name"> </component> <input type="bu ...

Create a search preview in JavaScript that emphasizes key information and provides a condensed overview

I am currently working on incorporating a feature that generates a highlighted and condensed preview of a provided text. Below is the code snippet I have so far: <div> Search: <input value='vestibulum' disabled/> </div> < ...