"Encountering a Type Error while implementing the $resource service in Angular

I encountered a strange error while working with angularjs. I incorporated the $resource module in angularjs to handle rest requests by adding this service:

$provide.service("CustomerService", ['$resource', function ($resource) {
    return $resource('/com/caspco/customers/:url:id', {}, {
        query: { method: 'GET', isArray: true, params: {id: '@id'}},
        find: { method: 'POST', isArray: true ,params:{url:'search'}},
        .......... other actions ..........
    });
}]);

In the backend server, I have a search method associated with the URL mentioned above for the find action that returns a JSON array. When attempting to call the find action in the controller using the following code:

service.$find().$promise.$then(function (res) {
    console.log("The resource is" + res);
}, function (error) {
    console.log("Error");
});

An error is thrown:

TypeError: (anonymous function) angular.js:2070
(anonymous function) angular.js:1516
k.$apply angular.js:2575
(anonymous function) angular.js:4323
o.event.dispatch jquery.js:3
r.handle

Answer №1

Service methods do not use the '$' character as a prefix, but resource methods returned from the service do. The 'then' method on the $promise property does not require the '$' prefix.

Improving the syntax in this way should set you in the right direction.

For more information, check out the official Angular documentation.

Answer №2

To begin, your code for invoking the service should be updated as follows:

service.retrieve().$promise.then(function (result) {
  console.log("data is" + result);
}, function (err) {
  console.log("error");
});

Another important point to consider is whether your response is truly an array. I made a mistake in assuming that the data returned from the backend was an array of objects. In reality, the backend was encapsulating them within a Response object before sending them back, causing Angular to receive an object containing an array instead.

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 I transfer variables between controllers using a service in AngularJS?

I am trying to pass a variable between controllers using a service. Below is the implementation of the service that passes the variable (in this case, a song id): 'use strict'; angular.module('PortalApp') .service('ActionbarSer ...

`The modal window fails to appear when triggered by ng-click`

I'm attempting to implement a modal popup window in my Angular application. Despite displaying the names, clicking on them does not trigger the modal to show up. Here's the code snippet: HTML: <div ng-app="app"> <div ng-repeat="cus ...

Tips on transferring HTTP data from a service to a controller in AngularJS

var locationListCtrl=function($scope, loc8rData){ $scope.message = "Looking for nearby places"; loc8rData .success(function(data){$scope.message = data.length > 0 ? "" : "No locations Found"; ...

Issue with Bourbon Bitters detected post-installation

Deciding to experiment with the Bourbon Sass framework, I embarked on the installation process. To use it in conjunction with yeoman/angular-generator, I had to downgrade Bourbon to v3.2.1 and Neat to v1.5 to avoid compilation errors. After the downgrade ...

``Promise rejection triggered when a boolean value is passed to $q.when`

In the code snippet below, $q.when is used to resolve a promise with either true or false. It is known that $q.when will always resolve and never be rejected. When passing a boolean value to this segment, it is observed that the error callback function is ...

Develop a Windows 8.1 Store App using VS Cordova and AngularJS

After downloading and implementing the two AngularJS demos from the links below, The demos functioned properly on WP8 and Android devices. However, upon deployment to Windows 8 Store App, the input box malfunctioned in both cases. I attempted using both ...

Renewed Promises: Exploring Promises in Angular JS

Revised with HTTP and initial code inspired by requests/Refer to the end of the post: Lately, I have been seeking help from the amazing SO community as I navigate through my AngularJS learning journey. I used to be a traditional C programmer but recently ...

Unable to retrieve information from the API despite successfully establishing a connection

I have been attempting to establish a connection between backend Laravel and frontend AngularJS using an API and AJAX $http method. The API connection works fine, but I am facing an issue where the data is not displaying in the ng-repeat method. I am unsur ...

eliminate empty lines from csv files during the uploading process in Angular

I have implemented a csv-reader directive that allows users to upload a CSV file. However, I have noticed an issue when uploading a file with spaces between words, resulting in blank lines being displayed. Here is an example: var reader = new FileReader ...

Updating the Angular checkbox does not trigger a complete digest cycle when clicking to show the template

Is there a way to trigger a full digest cycle when clicking a checkbox, rather than when it loses focus? I am facing an issue where the checkbox click event only triggers the local scope for the directive it is contained within. I need other directives to ...

Variable Scope is not defined in the TypeScript controller class of an AngularJS directive

I have implemented a custom directive to wrap ag grid like so: function MyDirective(): ng.IDirective { var directive = <ng.IDirective>{ restrict: "E", template: '<div style="width: 100%; height: 400px;" ag-grid="vm.agGrid ...

Executing Promises in an Array through JavaScript

LIVE DEMO Here is a function provided: function isGood(number) { var defer = $q.defer(); $timeout(function() { if (<some condition on number>) { defer.resolve(); } else { defer.reject(); } }, 100); return defer.pro ...

Dealing with Content-Range for pagination in Restangular: A comprehensive guide

When working with an API that returns the header "Content-range" for lists, how can I efficiently retrieve and parse this header value using Restangular? Do I need to create a custom function for this task? Is there an existing method in Restangular that ...

Using the ControllerAs syntax in conjunction with $scope methods

Currently working on incorporating the controllerAs syntax into AngularJS 1.3 Here is how I'm starting my function declarations: function() { var myCtrl = this; myCtrl.foo = foo; // Successfully implemented myCtrl.$on("foo", bar); // Enc ...

Setting a value to a variable in AngularJS is crucial for proper data

How come I'm encountering difficulty in assigning a value to $rootScope when using the code below? fetchIp().then(function(response){ $rootScope.nodeIp = (response.length == 0 ? "localhost" : response[0]); }); var root = 'http://& ...

How can data be passed from a directive to a controller in Angular?

I am currently working on implementing a directive pagination feature and I need to pass the current page number from the directive to a controller in order to run a specific function with this argument. However, I keep getting an 'undefined' err ...

gulp-angular-protractor experiences a fatal error with code 135

I am facing an issue while trying to execute end-to-end tests on an Angular 1.x system. Whenever I attempt to run gulp-angular-protractor tests, I encounter the following error: [TIME] E/launcher - Process exited with error code 135 [TIME] gulp-angular-pr ...

What is the significance of using $timeout in order to activate a watch function?

There is an interesting phenomenon happening with my directive. It watches the height of an element that is being updated by a controller using a factory method to retrieve data. Strangely, unless I include a $timeout in that factory function, my watch doe ...

Preserving alterations to media files using an image cropper

I've created a special controller for an image cropping tool that pops up over a media item in the content section. Right now I can manipulate the crops in the overlay, but when I click "Save Crops", the changes don't stick. However, if I use the ...

Step-by-step guide on serving index.html for angularjs and other frameworks using a server

After scouring Stack Overflow and various forums without success, I finally stumbled upon a solution that worked for me. I wanted to share it here in case it helps someone else :) This solution is specifically tailored for the folder structure outlined be ...