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

What is the best way to start data in an Angular service?

I'm currently navigating my way through building my first Angular application. One of the services I am using needs to be initialized with a schema defined in its constant block, but the schema/configuration is not yet finalized. Therefore, I am perfo ...

apply a course to the designated element

Alright, I have this piece of code that deals with session and page requests. // Let's start our session session_start(); // Now let's check if there is a page request if (isset($_GET['page'])) { // If there is a requested page, we ...

Filter a nested array in AngularJS and retrieve the parent object as the result

I've recently started experimenting with AngularJS to create checkbox filters for my wine store. Here is an example of an item in my store: { "id": 17, "name": "Ermelinda Freitas Reserva", "tag_ids": [40, 12, 56, 6, 60], " ...

Display the variable on the document by clicking the button

Hello, I'm new here so please forgive me if I make any mistakes. I am working with the following PHP code: <?php $quoteFile = "quotes.txt"; //Store quotes in this file $fp = fopen($quoteFile, "r"); //Open file for reading $content = fread ...

Dealing with redirecting to the login page in Angular

I recently started working with Angular and I feel completely lost. My initial task involves making a simple Rest-GET request, but the destination is located behind an external login page. This results in my request being redirected to the external page a ...

Ensure that the form is validated even when setState is not executed immediately

I am currently working on a form in React and I am facing an issue with validation. When the Submit Form button is clicked without filling in the input fields, an error should be displayed. This part is functioning correctly. However, even when the fields ...

Encountering an issue while attempting to send an image through JavaScript, jQuery, and PHP

I'm currently attempting to upload an image using JavaScript/jQuery, but I am unsure of how to retrieve the image in order to send it to a server (PHP). I have a form containing all the necessary information that I want to save in MySQL, and I use jQu ...

What is the best way to set up a simple example using a Node Stream.Readable?

I am currently exploring the concept of streams and encountering some difficulties in making it work properly. For this scenario, my goal is to send a static object to the stream and then pipe it to the server's response. This code snippet shows my ...

Versatile route able to handle any request thrown its way

My Node.js app is up and running smoothly using the Express.js framework. All routes in my application are set to post routes, such as: app.post('/login', function(req, res){ //perform login validation }); app.post('/AppHomepage', fun ...

Monitor the fullscreenChange event with angularJs

Utilizing a button to activate fullscreen mode for a DOM element using the fullscreen API is functioning correctly. The challenge arises when exiting fullscreen mode, requiring the listening for the fullscreen change event in order to resize the DOM elemen ...

Unable to successfully import an external HTML file that contains a script tag

I am currently experiencing an issue with my index.html <!doctype html> <html lang="en"> <head> <meta charset="utf-8> <title>MyApp</title> <link rel="import" href="./common.html"> </head> <body> ...

Learn how to easily modify a value in a CVS file by simply clicking on the data point on a highcharts graph

Is there a way to update my CSV file by clicking on a graph? I want to be able to create a graph from data in the same CSV file and then, when I click on a point, set that point to zero on the y-axis and update the corresponding value in the CSV file to 0. ...

What are some techniques for preventing Null Pointer Exception errors?

Currently, I am working on a project that involves creating a form with a dropdown field for categories. Based on the chosen category, I need to populate a second dropdown called subcaste using AJAX. To achieve this, I have implemented a method that disab ...

A Vue element that has multiple exact click handlers will consistently trigger the click.exact method when clicked with system modifiers

According to the information found at https://v2.vuejs.org/v2/guide/events.html#exact-Modifier, I am attempting to build an element that triggers different methods based on additional keys pressed at the time of clicking. <span @click.exact="method ...

Using AngularJS and ServiceStack webservice, perform the "get('url')" operation

I'm completely new to AngularJS and I'm attempting to retrieve some JSON items from a webservice I quickly set up using ServiceStack. When I enter the URL in the browser, I can see the JSON object without any issues. However, for some reason Angu ...

Newbie in JavaScript seeking help with JSON indexing: What could be causing my script using (for ... in) to fail?

Not being a seasoned Javascript coder or very familiar with JSON, my approach may seem naive. Any recommendations for better solutions are appreciated. Below is the code I've written: <!DOCTYPE html> <html> <head> <script& ...

Measuring the success of Vuejs app

Seeking performance metrics for a Vue application. Interested in metrics for the entire app as well as specific components. I am aware of using Vue.config.performance = true; to enable performance monitoring through dev tools, and I have considered utiliz ...

Expand and enhance your content with the Vue Sidebar Menu plugin

Recently, I integrated a side-bar-menu utilizing . My goal is to have a sidebar menu that pushes its content when it expands. Any suggestions on which props or styles I should incorporate to achieve this effect? Below is my Vue code: <template> ...

Error message encountered when trying to access a specific URL due to CORS restrictions

Currently, I am executing my code utilizing Java and AngularJS. The server is being hosted on port http://localhost:8080. Upon accessing http://localhost:8080/data, the following error is encountered: An XMLHttpRequest attempt to load ? has failed. ...

"Troubleshooting issue with AngularJS ng-repeat order by functionality based on

I am currently trying to sort my ng-repeat by descending date order, with the newest items appearing first. Despite my efforts, I have been unable to achieve this. I have carefully checked for any errors in quoting, but still no luck. I've attempted ...