Scope challenges with making multiple rest calls in Angular.js

As a beginner in Angular.js, I am facing an issue with $scope not receiving additional value from one of two $resource rest calls. Below is the code snippet:

controller: function ($scope, $modalInstance, $route) {
            $scope.server = {}

            $scope.submit = function () {
                //AddNewServer is a $resource service
                AddNewServer.post($.param({
                    'name': $scope.server.name,
                    'ip': $scope.server.ip,
                    'port': $scope.server.port
                }));

                //ServerStats is a $resource service
                ServerStats.postServerStats(function success(data) {
                    $scope.server.bytesIn = data.returnValue.bytesIn
                }, function err(err) {
                    console.log("Error: " + err)
                })

                $modalInstance.dismiss('cancel');
                $route.reload()

                //BELOW LOG RETURNS Object {name: "asd", ip: "asd", port: 2} NO bytesIn
                console.log($scope.server) 
            }

            $scope.cancel = function () {
                $modalInstance.dismiss('cancel');
                $route.reload()
            };
        }

I need help on how to include bytesIn from my other service call into my server object. I understand it might be a simple fix, but I appreciate any assistance during this learning phase. Thank you.

Answer №1

Make sure to keep in mind that your postServerStats() call is asynchronous, meaning that the success function may not have been executed by the time you reach the console.log($scope.server) statement.

To avoid this issue, place the console.log($scope.server) inside your success function, right after assigning $scope.server.bytesIn.

You might want to consider adding more functionality within the postServerStats() callback for better control over the asynchronous behavior.

Alternatively, explore using Angular promises for a more structured approach.

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 show an error message on a webpage using jQuery within a PHP environment?

I have a form in HTML that includes a submit button for posting status on a page. When a user clicks the submit button without entering anything into the form field, I want PHP to display a simple error message on the same page saying "This status update s ...

Disabling 'Input Number' feature is ineffective in Firefox browser

Is there a way to prevent the input value from changing when the up or down arrow is held, even if the input is disabled? I want to retain the arrows without allowing this behavior on Firefox. Give it a try: Press the up arrow. After 5 seconds, the input ...

Pattern matching to verify a basic number within the range of [0-6]

const number = '731231'; const myRegex = /[0-6]/; console.log(myRegex.test(number)); Could someone provide some insight into this code snippet? In my opinion, the regular expression [0-6] should only match numbers between 0 and 6. However, i ...

Is it frowned upon or restricted in contemporary Web development to incorporate dots (`.`) in HTTP query string parameters and form field names?

Recently, I developed an HTTP API endpoint for database searching which follows this format: GET /orders?created_by.name=John&delivery_estimate.start=2022-06-01 However, our web frontend developers are facing a challenge. They claim that existing Reac ...

Is it possible to adjust table rows to match the height of the tallest row in the table?

I've been attempting to ensure that all table rows have the same height as the tallest element, without using a fixed value. Setting the height to auto results in each row having different heights, and specifying a fixed value is not ideal because the ...

The TypeScript compiler is searching in an external directory for the node_modules folder

My angular 2 project is located in the directory /c/users/batcave/first_project. In that same directory, I have various files such as index.html, systemjs.config.js etc., and a node_modules folder that only contains @types and typescript. This means my @a ...

Implement a hover animation for the "sign up" button using React

How can I add an on hover animation to the "sign up" button? I've been looking everywhere for a solution but haven't found anything yet. <div onClick={() => toggleRegister("login")}>Sign In</div> ...

Confidential data in Module Design

I'm curious about the concept of private variables in JavaScript. How is it that I can still access a private variable through a public method and redefine the properties of the module? For example: var aModule = (function() { var privateVar = 1 ...

What is preventing me from installing react-router-transition on the 1.4.0 version?

$ npm install -S <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="8dffe8eceef9a0ffe2f8f9e8ffa0f9ffece3fee4f9e4e2e3cdbca3b9a3bd">[email protected]</a> npm ERROR! code ERESOLVE npm ERROR! Unable to r ...

Troubleshooting issue with downloading files in Spring Boot and Angular 2

I've encountered an issue with downloading a file from Spring Boot using Angular2. The code snippet from Spring Boot originates from this Stack Overflow post about returning generated PDF using Spring MVC. Strangely, I can download the file directly ...

Identifying the Back Button in Vue-Router's Navigation Guards

For my specific situation, it is crucial to understand how the route is modified. I need to be able to detect when the route changes due to a user clicking the back button on their browser or mobile device. This is the code snippet I currently have: rout ...

Error encountered in Three.js when using multiple canvases and loading JSON geometry

I have been working on creating multiple views and came across an example code here which worked flawlessly when I tried it. However, when I replaced the geometries with ones I created in Blender, I encountered an error: Cannot read property 'length ...

How can I replicate the function of closing a tab or instance in a web browser using Protractor/Selenium?

I want to create an automated scenario where a User is prompted with an alert message when they try to close the browser's tab or the browser itself. The alert should say something like "Are you sure you want to leave?" When I manually close the tab ...

Running a Node.js worker on an Amazon ECS-hosted server: A step-by-step guide

Our team is currently running a node server on Amazon ECS that receives up to 100 hits per second. Due to the single-threaded nature of JavaScript, we are hesitant to block the event loop. As a solution, we are looking to implement a worker that can peri ...

What could be causing the repeated calls to a computed function in vuejs?

In my Vuejs application, I start by fetching initial data and setting it in the store: const app = new Vue({ router, store, mounted: function() { var that = this; $.get("/initial_data/", {}, function(data) { that.$s ...

Tips for resolving the UNABLE_TO_GET_ISSUER_CERT_LOCALLY issue while attempting to install Sentry using npm or curl

https://i.stack.imgur.com/G8hfZ.png curl -sL -k https://sentry.io/get-cli/ | bash Even though I've specified not to verify the certificate with -k, I'm still facing issues trying to install it. The script is supposed to automatically install sen ...

Having trouble updating state in React after making a fetch request

I am encountering an issue with setting the current user after a successful login. Even though the login process is successful and the data is accurate, I am unable to set the state as the user data appears to be empty. UserContext.js import React, { useC ...

Find the string "s" within a div element aligned vertically, using Popper

Currently utilizing Popper from Material-UI <Popper id={"simplePopper"} open={true} style={{backgroundColor: 'red',opacity:'0.5',width:'100%',height:'100%'}}> <div style={{height:"100%", ...

Creating an infinite loop animation using GSAP in React results in a jarring interruption instead of a smooth and seamless transition

I'm currently developing a React project where I am aiming to implement an infinite loop animation using GSAP. The concept involves animating a series of elements from the bottom left corner to the top right corner. The idea is for the animation to sm ...

Angular7 & Electron: Resolving the Issue of Loading Local Resources

I am encountering difficulties while working with electron. Although I can successfully load my project using ng serve, I encounter an error when attempting to open it with electron as shown in the developer tools Not allowed to load local resource: fil ...