I am using init as follows
$scope.init = function () {
$scope.getAllDetails();
};
$scope.getAllDetails= function () {
$http({
method: "GET",
url: "api/endpoint"
}).then(function mySuccess(response) {
$scope.processData();
}, function myError(response) {
console.log(response.statusText);
}
);
};
$scope.processData() = function() {
//Logic to calculate var1
// var1 is then passed to $scope.getID to make call to Service1.getId(var1)
}
I have my first function which returns a promise:
$scope.getID = function() {
return Service1.getId("abc").then(function(response){
// In above line. Instead of manually passing `abc` I want to
//pass it as variable var1
// The desired call should be as below.
//But var1 is having null here
//return Service1.getId(var1).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;
});
};
The second function returns 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;
});
};
Then chaining the two promises:
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);
});
Problem:
The problem I am facing is related to var1 in $scope.processData()
The var1 is always having null value within $scope.getID
the var1 value is undefined
Sounds like this could be a problem with closures. A function will have access to the containing closures of the code where it was defined, not where it is called.
Is var1 truly
null, or is it in factundefined? If it'sundefined, probably what you need to do is make getId take var1 as an argument instead of relying on pulling the reference from the containing closure (which will not work for the reason stated above). If it's trulynull, then the problem probably lies in the code that calculates var1, which you've omitted.EDIT: The
getID()function would look very similar, but it would start like this:Instead of this:
And to call it you would probably do something like this: