How to pass global variable value from one function to another function in angular?
I have 2 global variables as:
$scope.genewtId = null;
$scope.data1 = null;
I have 2 angular functions which look as below:
$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){
// here response is having an error
$scope.data1 = response.data;
console.log($scope.data1.toString());
}, function(error){
console.log(error.statusText);
});
};
When I pass value of $scope.genewtId
from one function to another function, I get an error
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, console.log($scope.genewtId);
is returning a value 787651
which means it is not null.
Please suggest if it can be implemented using $rootScope.$broadcast
The promises from the two services need to be chained
Modify the first function to return a promise:
Modify the second function to both return a promise and accept an argument:
Then chain the two promises:
By using the
.then
method of thegetId
promise, the code waits for theid
value to arrive from the server before making the request togetDetails
.Because calling the
.then
method of a promise returns a new derived promise, it is easily possible to create a chain of promises. It is possible to create chains of any length and since a promise can be resolved with another promise (which will defer its resolution further), it is possible to pause/defer resolution of the promises at any point in the chain.For more information, see
It seems like the exception is coming from the server side.
It is getting printed on the console due to
console.log(error.statusText);
You need to verify the logic when the value is used in the API.
The only reason I can think of is because of
asynchronous
call ofpromises
. What's happening is that :Somehow, you are calling
Service2.getDetails($scope.genewtId)
before the value of$scope.genewtId
has been set after the promise completion ofService1.getId("abc").then
, and so the value remainsnull
Try:
Even, if this approach works, I would strongly suggest you to implement the function calls in a better way because
$scope.getDetails()
is dependent on$scope.getID()
for setting value of$scope.genewtId
.If you want suggestion on how to implement it, please update the question with the use case and some more code
Update
Using service
In service.js
controller.js