Tips for transferring data from one asynchronous function to another in AngularJS

How to transfer a global variable value between two Angular functions?

Here are the two global variables:

$scope.genewtId = null;
$scope.data1 = null;

The two Angular functions in question are:

$scope.getID = function() {
    Service1.getId("abc").then(function(response){
        $scope.genewtId = response.data[0].Id;
        console.log($scope.genewtId);

    }, function(error){
        console.log(error.statusText);
    });
};

$scope.getDetails = function() {
    Service2.getDetails($scope.genewtId).then(function(response){
        // encountering an error with the response
        $scope.data1 = response.data;
        console.log($scope.data1.toString());
    }, function(error){
        console.log(error.statusText);
    });
};

When attempting to pass the value of $scope.genewtId from one function to another, an error is being received:

message: "Failed to convert value of type 'java.lang.String' to required type 'java.lang.Integer'; nested exception is java.lang.NumberFormatException: For input string: "null"

However, the output of console.log($scope.genewtId); shows a value of 787651, indicating that it is not null.

If there's a way to implement this using $rootScope.$broadcast, please advise.

Answer №1

The importance of chaining promises in web development

To enhance the functionality of your code, consider modifying the first function to return a promise:

$scope.getID = function() {
    return Service1.getId("abc").then(function(response){
        $scope.genewtId = response.data[0].Id;
        console.log($scope.genewtId);
        return response.data[0].Id;
    }, function(error){
        console.log(error.statusText);
        throw error;
    });
};

Additionally, adapt the second function to both return a promise and accept an argument:

$scope.getDetails = function(id) {
    var genewtID = id || $scope.genewtId;
    return Service2.getDetails(genewtId).then(function(response){
        $scope.data1 = response.data;
        console.log($scope.data1.toString());
        return response.data;
    }, function(error){
        console.log(error.statusText);
        throw error;
    });
};

Subsequently, create a chain of promises by connecting the two functions:

var promise = $scope.getId();

var promise2 = promise.then(function(id) {
                   return $scope.getDetails(id);
               });

var promise2.then(function(data) {
     console.log(data);
}).catch(function(error) {
     console.log(error);
});

Utilizing the .then method facilitates synchronization between promises, ensuring data is retrieved sequentially. You can extend these chains indefinitely, pausing or postponing resolution as needed.

For further insights, refer to:

Answer №2

One potential reason for the issue could be due to the asynchronous nature of promises. The scenario is as follows:

The function

Service2.getDetails($scope.genewtId)
may be getting called before the value of $scope.genewtId is properly set after the promise from Service1.getId("abc").then completes, resulting in the value remaining as null.

To address this problem, consider the following approach:

$scope.getID = function(isCalledAfterDetails) {
    Service1.getId("abc").then(function(response){
        $scope.genewtId = response.data[0].Id;
        console.log($scope.genewtId);
        if(isCalledAfterDetails && $scope.genewtId !== null){
            $scope.getDetails();
        }

    }, function(error){
        console.log(error.statusText);
    });
};

$scope.getDetails = function() {
    if($scope.genewtId === null){
        $scope.getID(true);
    }else{
        Service2.getDetails($scope.genewtId).then(function(response){
            // an error may occur here with the response
            $scope.data1 = response.data;
            console.log($scope.data1.toString());
        }, function(error){
            console.log(error.statusText);
        });
    }

};

While this solution might work, it's advisable to improve the way you structure these function calls. Ensure that $scope.getDetails() does not excessively rely on $scope.getID() for setting the value of $scope.genewtId.

If you require further assistance in implementing a better solution, kindly update your question with specific use cases and additional code snippets.

Updated Solution

$scope.getID = function() {
    Service1.getId("abc").then(function(response){
        $scope.genewtId = response.data[0].Id;
        $scope.getDetails();
    }, function(error){
        console.log(error);
    });
};

$scope.getDetails = function() {
        Service2.getDetails($scope.genewtId).then(function(response){
            // an error may occur here with the response
            $scope.data1 = response.data;
            console.log($scope.data1.toString());
        }, function(error){
            console.log(error.statusText);
        });        
};

Utilizing a Service

In your service.js file

getDetails = function(id){
    var deferred = $q.defer();
    $http.get('/user/'+id).then(function(response){
        var newId = response.data[0].Id;
        $http.get('/user/details'+newId).then(function(details){
            deferred.resolve(details)
        })
    })      
    return deferred.promise;
}

In your controller.js file

$scope.getDetails = function() {
        MySvc.getDetails("abc").then(function(response){
            console.log(response) // your details here
        }, function(error){
            console.log(error.statusText);
        });        
};

Answer №3

Looks like the issue is originating from the server side.

An error occurred while trying to convert a 'java.lang.String' to an 'java.lang.Integer'; this resulted in a NumberFormatException with the input string being "null".

The message is showing up on the console because of console.log(error.statusText);

You should double-check the logic when using the value in the API.

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

Modify the appearance of an element within an array upon selection by comparing it with a separate array

In my code, there is an array called tagList that contains a list of objects. When one of these objects is clicked on, it gets added to another array named selectedTags. var selectedTags = []; export default class RegisterTags extends Component { con ...

Issue: [$injector:unpr] Provider not found: RequestsServiceProvider <- RequestsServiceFor more information on this error, please visit the website: http://errors.angularjs.org

Despite defining my service name in all necessary places, I am still encountering the error mentioned above. Below is my app.js: var app = angular.module('ionicApp', [ 'ionic', 'ngCordova', 'checklist-model' ]) ...

Excessive CPU usage caused by a patch in jQuery dealing with regular expressions

Working on a project developed by an unknown individual has presented some challenges. Without any means of contact with this person, I noticed that the browser's CPU consumption spikes significantly upon loading the page. Upon further investigation, ...

The top choice for AngularJS: A trustworthy JSON viewer and editor module

Currently, I am working on enhancing my app by incorporating a json editor feature. I would appreciate any recommendations on which module you have experience with and believe is both stable and effective. The data I am working with is already in json for ...

AngularJS and synchronized queueing of API requests

I am attempting to develop a synchronized queue for API requests using AngularJS. class x { public y() { ... restRequest(); } } I have this class, along with a whiteboard canvas. When I drop an entity onto the canvas, the method &a ...

Similar to ng-src, how to handle "Value" attributes in AngularJS

I am currently working with AngularJS and I want to include a vimeo link on one of my pages. The challenge is that depending on whether the user is accessing the page through HTTPs or HTTP, we need to adjust the URL accordingly. <div class="video"> ...

Guide to creating intricate designs on an HTML5 Canvas, one pixel at a time

Imagine a scenario where there is a 900x900 HTML5 Canvas element involved. In this case, there is a function named computeRow, which takes the row number as a parameter and returns an array of 900 numbers. These numbers represent colors ranging from 0 to ...

The contact form displays a confirmation message indicating successful submission, however, it fails to actually send the email

Having issues with a PHP script I created for the contact page on my website. After a user fills out and submits the form, they see a success message but the email is not sent. Can someone review this script and point out where I went wrong? <?php ...

What is the best way to show and hide text by toggling a link instead of a button?

I need help with toggling between two different texts when a link is clicked. I know how to achieve this with a button in JQuery, but I'm not sure how to do it with a link. <h1>Queries and Responses</h1> <p>Query: What is the larges ...

Looking to adjust the fill pattern dynamically

I previously implemented this code: Is there a way to modify the fill image on my 3 buttons to display in 3 distinct colors instead? ...

Encountering the issue of "Unknown provider" while injecting Angular modules

After following a tutorial on organizing an Angular project, I came up with a structure where I have a ng directory containing all my controllers, services, and the routes.js file. These are then bundled together into an app.js through my configuration in ...

Missing data: Node JS fails to recognize req.body

I've looked through various posts and I'm feeling quite lost with this issue. When I run console.log(req), the output is as follows: ServerResponse { ... req: IncomingMessage { ... url: '/my-endpoint', method: &a ...

Utilizing unique symbols to dynamically add form elements to an HTML page with jQuery's append method

I am facing an issue with creating forms on my HTML page. Here is an example of how I am trying to do it: <form action="/tasks/<%= allTasks.e[0].id %>/delete" method="POST"> <button class="deleteTask">Delete</button> </f ...

Complete my search input by utilizing ajax

It's only been 30 minutes since my last post, but I feel like I'm making progress with my search posts input: I've developed a model that resembles this: function matchPosts($keyword) { $this->db->get('posts'); ...

"Guidelines for implementing a post-login redirection to the homepage in React with the latest version of react-router (v

I am facing an issue where I am unable to redirect to the Home Page when I click the "Login" button during my React studies. Despite trying all possible methods for redirects, none of them seem to work. The function that is executed when I click the "logi ...

Building a single page web application using TypeScript and webpack - a step-by-step guide

For a while now, I've been working on single page applications using Angular. However, I'm interested in creating a single page application without utilizing the entire framework. My goal is to have just one .html file and one javascript file, w ...

After a push to the router, scrolling is disabled

While working on a Vuejs project, I encountered an issue when trying to change the page of my PWA using this.$router.push();. It seems to work fine everywhere else except when doing it from a modal within a component. The pushed page loads but scrolling is ...

Issue with PrimeFaces radiobutton styles not updating after being clicked programmatically

My setup includes a p:selectOneRadio constructed like this: <p:selectOneRadio id="positionRadio" value="#{employeeBean.empPosition}" converter="#{empPositionConverter}" layout="custom" required="true" requiredMessage="Please select ...

Analyzing JSON information and presenting findings within a table

Requesting user input to generate a JSON object based on their response. Interested in showcasing specific details from the object in a table format for user viewing. Questioning the efficiency and clarity of current approach. My current progress: In HTM ...

I'm looking for a way to seamlessly incorporate PayPal Standard into my app with AngularJS. Any suggestions

I am in the process of integrating PayPal payment into my app. After completing all the necessary steps within my app, I want to be able to check out on the PayPal site and then return to my app after a successful transaction. Can someone provide guidance ...