Retrieving information from $resource.get() in AngularJS

Working with JSON and XML in AngularJS

{
  itemNumber: "T00000245",
  lotNumber: "00004"
}

<jdeSerials>
  <itemNumber>T00000245</itemNumber>
  <lotNumber>00004</lotNumber>
</jdeSerials>

Dealing with Asynchronous Calls in AngularJS

//Searching a product with serial number/LOTN
$scope.searchProduct = function () {
    var lotNumber = $scope.jdeSerials.lotNumber;
    console.log("searchProduct---->" + lotNumber);//log-->searchProduct---->00004


    $scope.JdeSerials = lotnService.get({id: lotNumber}, function() {
      console.log($scope.jdeSerials);//log-->[object Object] 
      console.log($scope.jdeSerials.itemNumber);//log-->undefined!!!!!

    });

//var itemNumber = $scope.jdeSerials.itemNumber;
//$scope.jdeproduct = productService.get({id: itemNumber});

};

Creating an AngularJS service for handling API calls

angular.module('lotnService', ['ngResource'])
    .factory('lotnService', ['$resource',
        function ($resource) {
            console.log('------lotmService-----');
            return $resource(
'http://localhost:8080/RMAServer/webresources/com.pako.entity.jdeserials/:id',
                    {},
                    {

                        update: { method: 'PUT', params: {id: '@lotNumber'} }
                    });
        }]);

Question:

How can I access the value of $scope.jdeSerials.itemNumber? Is there a better approach to handling multiple asynchronous GET requests like splitting them into separate services? It seems that the issue is related to the asynchronous nature of the GET method, but what is the optimal solution for managing such scenarios?

EDIT/update:

I updated the service call as follows:

$scope.JdeSerials =   lotnService.get({id:lotNumber})
.$promise.then(function(jdeSerials) {
    $scope.jdeSerials = jdeSerials;
    console.log("1--------------->Item Number:" + $scope.jdeSerials.itemNumber);
 });

I was able to retrieve the Item Number, BUT encountered the following error message:

TypeError: Cannot read property 'then' of undefined

Answer №1

Implement a get method within your resource.

angular.module('lotnService', ['ngResource'])
  .factory('lotnService', ['$resource', function ($resource) {
     return $resource(  'http://localhost:8080/RMAServer/webresources/com.pako.entity.jdeserials/:id',
                {},
                {
                    get: { method: 'GET', params: {id: '@lotn'}},
                    update: { method: 'PUT', params: {id: '@lotn'} }
                });
    }]);

Next, in your controller, utilize the get method from the service:

lotnService.get({id:lotn}).$promise.then(
 function(jdeSerials) {
   $scope.jdeSerials = jdeSerials;
   console.log("1--------------->LITM:"+$scope.jdeSerials.litm);
});

Answer №2

Which version of AngularJS are you currently using?

Can you confirm if the following code snippet is functioning correctly?

lotnService.get({id: lotn}).then(
    function(jdeSerials) { ... }
);

(excluding the usage of $promise)

While reviewing the documentation and the source code of angular-resource.js for older versions, it seems that there have been changes in syntax over time.

In the angular-resource.js 1.2.0 source:

The Resource instances and collection have these additional properties:
$promise: the {@link ng.$q promise} of the original server interaction that created this *instance or collection.

However, there is no mention of the $promise property in version 1.0.8.

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

Selenium and phantomjs failed to locate the specified element

When attempting to test an AngularJS application using Selenium and the PhantomJS driver, I encountered the following error message: [ERROR - 2016-06-27T09:42:57.040Z] Session [87123530-3c4b-11e6-bbdd-eb6d6096f6c5] - page.onError - msg: Error: [$injector: ...

Refresh your HTML by reloading the JavaScript source

In my Ubuntu setup, I've been using chart.js to generate a graph displaying the values from a pressure sensor on an HTML document. Most of the project is complete, but I've encountered a challenge for which I haven't found a satisfactory sol ...

Out of nowhere, JavaScript/jQuery ceased to function

Everything was running smoothly on my website with jQuery Ui until I changed the color, and suddenly everything stopped working. Any ideas why this happened? I even tried writing the JavaScript within the HTML file and linking it as a separate .js file, bu ...

Styling of global checkbox focus in Material UI (applied globally, not locally)

Currently experimenting with customizing the styling of a checkbox when it is in focus globally using Material-UI (react). At present, only default and hover styles are taking effect: MuiCheckbox: { colorSecondary: { color: 'green', & ...

Incorporating a middleware into a Node.js and Express application

In my Node.js REST API project with Express, I have several files that play different roles: app.js router.js controller.js Within app.js: var routes = require('./source/router'); ....... app.use('/application', routes); Within rou ...

What could be causing my jQuery function to not correctly update the class as specified?

Presented is a snippet of script that I execute at a specific moment by echoing it in PHP: echo "<script>$('.incorrect-guesses div:nth-child(2)').removeClass('empty-guess').addClass('incorrect-guess').text('2' ...

The Slice method is malfunctioning after the array has been filtered

I am currently working on creating a news portal app using Next JS, Redux, mongoose, and Express. My Issue is: While I am able to filter specific items from an array successfully, I encounter problems when attempting to display a specific number of items, ...

Looking to display database information using javascript

Currently, I am working on a project involving PHP code where I retrieve variables from an input and utilize AJAX. Here is the code snippet: $.ajax({ type: "GET", url: "controller/appointment/src_agenda.php", data: { function: "professional", ...

What is the best way to close all modal dialogs in AngularJS?

Back in the day, I utilized the following link for the old version of angular bootstrap: https://angular-ui.github.io/bootstrap/#/modal var myApp = angular.module('app', []).run(function($rootScope, $modalStack) { $modalStack. dismissAll( ...

Using a checkbox to sort through Google Maps markers

I want to create a filter for my google maps markers using checkboxes, inspired by this V3 example. Here's the HTML for the checkboxes: <form action="#"> Attractions: <input type="checkbox" id="attractionbox" onclick="boxclick(this,'a ...

What is the best way to include a class with Knockout JS?

After going through the basic Knockout tutorial and examining various examples, I decided to try it out myself on jsFiddle. However, I encountered some issues as my attempts did not quite work. The goal is simple - I just want to add the class open to a d ...

Dynamic header feature that maintains the aspect ratio of the logo image

Currently, I'm faced with the challenge of fixing the main grid on a website that I am currently working on. My objective is to minimize the use of media queries as much as possible. I am looking to ensure that the Logo Image maintains the height of ...

Evaluation of outgoing HTTP requests through acceptance testing was the primary focus

Is there a possibility for automated acceptance testing when specific network requests are required by a web application due to user interactions? This type of testing seems unconventional as online discussions and tutorials are lacking in this area. For e ...

Group the elements of the second array based on the repeated values of the first array and combine them into a single string

I have a challenge with two arrays and a string shown below var str=offer?; var names = [channelId, channelId, offerType, offerType, Language]; var values =[647, 763, international, programming, English]; Both arrays are the same size. I want to creat ...

Passing a variable between pages in PHP: a simple guide

In my *book_order* page, I allow users to input orders into a table called *order_management*. The order_id is auto-incremented in this table. After submitting the page, I need to pass the order_id to another page named *book_order2* where products can be ...

css: Apply this style to remove vertical space within a <table> when the table data contains multiple elements

In the field for table data, there is a blue square on top and an icon on the bottom. To view, please check out this JsFiddle link. The height of the td field measures at 26px due to a small vertical space between the elements: the blue_line div element ...

CORS issue encountered by specific user visiting the hosted website

I recently developed a bot chatting website using Django and React, which I have hosted on HOSTINGER. The backend is being hosted using VPS. However, some users are able to see the full website while others encounter CORS errors where the APIs are not func ...

What is the best way to align my header buttons in the center and move items to the far right of my toolbar?

My header currently displays as follows: https://i.sstatic.net/h8zDQ.png I am aiming to center the [LEARN MORE, ABOUT, RESOURCES, CONTACT] buttons in the middle of the navbar and align the profile icon and switch button to the far right of the page! I en ...

Prometheus nodejs app already contains a metric by that name

Encountering a problem where the metric has already been registered when attempting to publish metrics from a service. To work around this issue, the register.removeSingleMetric("newMetric"); method was used. However, this method clears the register and pa ...

Utilizing Correlated Filters in Conjunction with Firebase Database

I am struggling with a firebase query that requires adding a where() condition based on a certain criteria. Specifically, I want the where() clause to be included only if certain values are entered, otherwise the basic query should run as usual. However, ...