Troubles arise when using $resource without initializing it with the new operator

Trying to utilize the Angular promise API in my application has left me feeling a bit puzzled. I set up a factory as shown in the code snippet below:

factory('transport', function ($resource) {
    var baseUrl = "http://aw353/WebServer/odata/Payments";
    return $resource("", {},
        {
            'getAll': { method: "GET",params: {svcUrl:"@svcUrl"}, url: baseUrl + ":svcUrl" },
            'save': { method: "POST", params: {svcUrl:"@svcUrl"}, url: baseUrl+ "(:svcUrl)" },
            'update': { method: 'PUT', params: {svcUrl:"@svcUrl", key: "@key" }, url: baseUrl+ "(:svcUrl)" + "(:key)"},
            'query': { method: 'GET', params: {svcUrl:"@svcUrl", key: "@key" }, url: baseUrl +"(:svcUrl)" + "(:key)"},
            'remove': { method: 'DELETE',  params: {svcUrl:"@svcUrl", key: "@key" }, url: baseUrl + "(:svcUrl)" + "(:key)"}
        });
});

When incorporating this factory in a controller and defining the function as follows:

var getData = function () {
    (transport()).$getAll({svcUrl:"//BasicSettings"})
        .then(function (data) {
            $scope.DataSource = data.value[0];
            console.log($scope.DataSource.SystemName);
        });
}();

it encounters an error stating "Cannot read property '$getAll' of undefined". However, using the 'new' keyword like this

var getData = function () {
    (new transport()).$getAll({svcUrl:"//BasicSettings"})
        .then(function (data) {
            $scope.DataSource = data.value[0];
            console.log($scope.DataSource.SystemName);
        });
}();

solves the issue.

I comprehend the distinction between a constructor function and a regular function. Yet, I am puzzled as to why the promise API only functions in the latter scenario.
Could someone provide insight into the working mechanism behind this?

Answer №1

Give it a shot:

transport.getAll(...).$promise.then(...)

instead.

I understand the distinction between constructor functions and usual functions. However, I am puzzled as to why the promise API only works in the second scenario.

It's because the API is intentionally designed that way. You have access to both instance methods and class methods.

To instantiate, you must utilize the new operator to gain access to instance methods.

The $resoure() method is a factory that extends "$resource" and returns a constructor function with class methods. Instances of this constructor function hold instance methods.

function Resource(value) {
    shallowClearAndCopy(value || {}, this);
}

forEach(actions, function (action, name) {
    var hasBody = /^(POST|PUT|PATCH)$/i.test(action.method);

    Resource[name] = function (a1, a2, a3, a4) {
        var params = {}, data, success, error;
(...)

By inspecting the source code, we can see that class methods are dynamically created on the Resource constructor.

https://github.com/angular/angular.js/blob/master/src/ngResource/resource.js#L492

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

req.next does not exist as a function [END]

I am currently working on developing a website and I have encountered an issue in the dashboard stage. The error message TypeError: req.next is not a function keeps appearing, particularly when trying to create a subpage for the dashboard. I am utilizing t ...

AngularJS grid designed to emulate the functionalities of a spreadsheet

I have been facing challenges with Angular while attempting to recreate a spreadsheet layout in HTML using ng-repeat. Despite extensive research, I have not found a solution. My goal is to display data in a table format as shown below: <table> & ...

What is the best way to display only the current != wanted lines when using "npm outdated"?

Whenever I input npm outdated, it shows a similar output like this: Package Current Wanted Latest Location columnify 1.1.0 1.1.0 1.2.1 /usr/local/lib > npm > columnify cmd-shim 1.1.2 1.1.2 2.0.0 /usr/local/lib & ...

Tips for utilizing the "get" method in React to submit a form

Is there a way to submit a form using the "get" method to an external URL in react? Similar to how it is done in HTML like in this example: https://www.example.com/form But instead, to a third party URL...? Can I achieve something like this? The goal is ...

I'm looking for the location of the console.log output while running nodejs/npm start. Where

Just started working with react/node and using npm start to launch a server. The server is up and running, displaying my react code as expected. However, I'm facing an issue with debugging - my console.logs are not showing up in the browser console. I ...

assigning a CSS class to an input element based on a certain condition

My dilemma involves an input field for which I need to conditionally apply a CSS class. For instance, if firstName == undefined, I want to apply the CSS class ng-dirty. To achieve this, I attempted: <input required [(ngModel)]="customer.firstName" nam ...

Tips for rotating individual letters within a sentence on popular web browsers, including Chrome

Can you make a sentence appear with each individual letter rotating and getting larger? This is my approach: I decided to split the sentence into separate span elements, one for each letter. Then I used CSS transform -webkit-transform to animate the lette ...

Is there a way to determine the duration that a click was held down for?

When triggering an onClick event, I want to determine whether it was a single click or if the mouse button was held down for some time before releasing. This way, I can call the myTest() function within onClick="myTest()", which will log "mouse was click ...

JavaScript array remains unchanged

I have a sample of JSON data saved in the "data" variable. Here is the FORMAT : { "0" : {"names":"Pooja, Trivedi"}, "1" : {"names":"Pooja, Rooster"} } My objective is to create a map that can calculate the frequency of each name: Pooja = 2 Triv ...

AngularJS - Oops! There seems to be an issue: [ng:areq] The argument 'CustomersController' is invalid and cannot be found

Below is the content of my index.html file: <!DOCTYPE html> <html ng-app> <head> <title>Iterating Over Data</title> <link href="styles.css" rel="stylesheet" type="text/css" /> </head> <body ng-controlle ...

Implementing a vertical tabindex change in Material UI Dialogue table

My material UI dialogue contains a table: <Dialog open={open} onClose={handleClose} maxWidth={'xl'} aria-labelledby='scroll-dialog-title' aria-describedby='scroll-dialog-description' disa ...

Finding out the specific row that was clicked in a Jquery Mobile listview

I've searched everywhere and can't find a solution. How can I retrieve the value of a row tapped in a listview? This could be anything from the name to the index within the object. Currently, I have a function handling the tap event. I need to pa ...

Display a specific number of page indicators on the Flickity plugin

Currently, I am utilizing the flickity plugin to create a slideshow feature on my website. My goal is to display navigation dots on the images to facilitate user interaction. If you are interested, you can access the plugin through this link: I would lik ...

Unlocking ajax components using django

Currently, I am utilizing AJAX to retrieve Django model data and display the results. In my views.py file: def browse_jobs(request): keyword = request.GET.get('keyword', None) company = Company.objects.filter(title__icontains=keyword) ...

Ajax/PHP - unrecognized value in autofill

I have implemented this particular example to execute an ajax data query from a MySQL database, which returns a table. Currently, this setup functions correctly when text is manually entered into the input form. Example: The issue arises with the autocom ...

React Native's NativeBase checkbox component: Overlapping text causing the content to extend beyond the confines of the screen

I am having trouble getting the text inside a checkbox (using nativebase) to shrink. Does anyone know why this is happening? Do I need to add some flex properties? import React from "react" import {Box, Center, Checkbox, Heading, NativeBaseProv ...

Is there a way to customize jqwidgets jQuery grid cell classes/styles based on row ID and column name?

{ text: 'sell', datafield: 'Sales', width: '3%', columntype: 'button', filterable: false, cellsrenderer: function(row, columnfield, value, defaulthtml, columnproperties) { return &apos ...

A guide on retrieving the values of all child elements within an HTML element using Puppeteer

I have been exploring the capabilities of puppeteer and am trying to extract the values from the column names of a table. <tbody> <tr class="GridHeader" align="center" style="background-color:Black;"> <td cl ...

How can I obtain the model values for all cars in the primary object?

const vehicles={ vehicle1:{ brand:"Suzuki", model:565, price:1200 }, vehicle2:{ brand:"Hyundai", model:567, price:1300 }, vehicle3:{ brand:"Toyota", model ...

Converting every item's values into keys

Currently, my goal is to export all object values as keys specifically for a tree-shakable import system in a plugin I'm currently developing. The approach involves dynamically importing modules from various directories and subfolders, consolidating t ...