Parallel $http calls using same object - angularjs

I have the following function in a controller:
this.someFunction = function() {
var filter = {
type: 'E'
};
someService.httpPostFunction(filter).then(function(response) {
console.log(response);
});
filter.type = 'H';
someService.httpPostFunction(filter).then(function(response) {
console.log(response);
});
filter.type = 'W';
someService.httpPostFunction(filter).then(function(response) {
console.log(response);
});
};
This is the someService.httpPostFunction :
httpPostFunction: function(filter) {
var deferred = $q.defer();
var httpPromise = $http.post(url,filter)
.then(function(response) {
deferred.resolve(response.data);
}, function(error) {
deferred.reject(error.data);
});
return deferred.promise;
}
The someService.httpPostFunction returns me different data based on filter.type. I want them to run in parallel. However, this function behaves as if the filter.type is set to 'W' even on the first httpPostFunction call.
Creating copies of the filter variable, changing type of the copies and then passing the copies gives me correct results but this is not feasible. How do I get the code working correctly using the same variable?

You could use an array to store the promises and then use $q.all to catch all the promises something like below
this.someFunction = function() {
var filterObj = {
type: ['E', 'H', 'W']
};
var promises = filterObj.type.map(function(v) {
return someService.httpPostFunction(v);
});
$q.all(promises).then(function(response) {
console.log(response[0]); //type E
console.log(response[1]); //type H
console.log(response[2]); //type W
});
};

you can use $q.all to send multiple http request parallel
var filterObj = {
type: ['E', 'H', 'W']
};
var arr = [];
for(item in filterObj.type){
arr.push(someService.httpPostFunction(item))
}
$q.all(arr).then(function(responses) {
console.log( responses[0].data);
console.log( responses[1].data);
console.log( responses[2].data);
});

Related

How to make a double GET on angular 1.x

I want to do a doble Get using the return of the first one as input for the second one, is there a way to do this?
ExpedienteService.getExpediente(id).then(function(data) {
vm.expediente = data;
}).then(AutoService.getAuto1a5(vm.expediente).then(function(data) {
vm.autos = data;
})
);
thats what i got so far.
ExpedienteService.getExpediente(id).then(function(data) {
vm.expediente = data;
return AutoService.getAuto1a5(vm.expediente);
}).then(function(data) {
vm.autos = data;
});
You were close.
Say if you didn't want to save the first data into vm.experiente you could do.
ExpedienteService.getExpediente(id)
.then(AutoService.getAuto1a5)
.then(function(data) {
vm.autos = data;
})
function yourNewFunction() {
var deferred = $q.defer();
ExpedienteService.getExpediente(id).then(
function getExpSuccess(resp) {
var vm = {
expediente = resp.data;
};
AutoService.getAuto1a5(vm.expeidente).then(
function getAutoSuccess(resp) {
vm.autos = resp.data;
deferred.resolve(vm);
},
deferred.reject
}
},
deferred.reject
);
return deferred.promise;
}

Empty var in second service function

I have a service:
.service('VacanciesService', function($http) {
var vacancies = [];
var usedVacancies = [];
return {
getVacanciesForUniversity: function(university_id) {
return $http.get("http://jobs.app/api/vacancies/" + university_id).then(function(response){
vacancies = response.data.vcancies;
return vacancies;
}, function(error){
return error;
});
},
getRandomVacancy: function() {
console.log(vacancies);
}
}
})
This is the calling controller
.controller('jobsCtrl', function($ionicLoading, locker, UniversitiesService, VacanciesService) {
var vm = this;
user = locker.get('userDetails');
UniversitiesService.getUniversity(user.university.id).then(function(university) {
vm.university = university.university;
});
VacanciesService.getVacanciesForUniversity(user.university.id).then(function(vacancies) {
vm.vacancies = vacancies;
}, function error(error) {
});
vm.addCard = function(name) {
newVacancy = VacanciesService.getRandomVacancy();
};
vm.addCard();
})
And I can't figure out why the vacancies variable in in the console.log is empty in the second function? I assumed as it was set in the initial function (called prior) that it should be populated?
TIA!
if you call getVacanciesForUniversity getRandomVacancy like below, you will get empty array
VacanciesService.getVacanciesForUniversity(uniId)
VacanciesService.getRandomVacancy() //you will get empty
you must getRandomVacancy inside getVacanciesForUniversity returned promise
VacanciesService.getVacanciesForUniversity(uniId).then(function(){
VacanciesService.getRandomVacancy()
})
alo you misstype response.data.vcancies; instead response.data.vacancies;
The answer is READ YOUR CODE PROPERLY.
There was a glaringly obvious typo in my code that I missed from staring at it too long.
Big thanks to Daniel Dawes and aseferov for attempting to help!
In your service :
getVacanciesForUniversity: function(university_id) {
return $http.get("http://jobs.app/api/vacancies/" + university_id);
}
In your controller :
$scope.getVacancies = function () {
your_service.getVacanciesForUniversity().then(
function(response) {
if (response.status = 200) {
$scope.vacancies = response.data.vacancies;
}, function errorCallback (response) {
...
}
);
};
$scope.getVacancies(); // you call one time your function here
$scope.getRandomVacancy : function() {
console.log($scope.vacancies);
};

compare to object angular js

i have a problem with AngularJS I receive from api json that json contains a prod url and url prerpod I would make calls to these APIs to retrieve a new one json then compare the results to validate which are the same as the problem is that I have a 200 aPI test how can I do. Thank you in advance
ps I think the test objects with the method equals.
i have 100 object like this:
{
"ID": "1",
"URL_preprod": "url1",
"Preprod_bis": "url2",
"prod": "url3",
}
i need to check if the result of call is equals for each object.
function callAtTimeout() {
if ($scope.preprod && $scope.preprodBis) {
angular.equals($scope.preprod,$scope.preprodBis);
$scope.msg = "equals";
}}
$scope.test = function() {
if (tnrArray) {
for (var i = 0; i < tnrArray.length; i++) {
var urlPreprod = tnrArray[i].URL_preprod;
console.log(urlPreprod);
$http.get(urlPreprod).success( function(response) {
$scope.preprod = response;
console.log(response);
});
var urlPreprodBis = tnrArray[i].Preprod_bis;
console.log(urlPreprodBis);
$http.get(urlPreprodBis).success( function(response) {
$scope.preprodBis = response;
console.log(response);
});
$timeout(callAtTimeout, 3000);
}
var response1;
$http.get("/your/url").then(function(response) {
response1 = response;
return $http.get(response.prodUrl);
}).then(function(prodResponse) {
console.log(prodResponse);
console.log(_.isEqual(response1 , prodResponse)); // uses lodash
}).catch(function(badResponse) {
console.log("oops something went wrong", badResponse);
})
this should work - lodash is used to check for equality
TO DO THIS FOR 200 URLs ASYNCHRONOUSLY ...
var urlList = ['/path/url1','/path/url2','/path/url3'];
angular.forEach(urlList, function(url) {
var response1;
$http.get(url).then(function(response) {
response1 = response;
return $http.get(response.prodUrl);
}).then(function(prodResponse) {
console.log(prodResponse);
console.log(angular.equals(response1 , prodResponse));
}).catch(function(badResponse) {
console.log("oops something went wrong", badResponse);
})
});

Angularjs $http my second then before first then is done.

I am not sure what I am doing wrong here, but the Report.xls gets downloaded before report.students gets updated.
How can I make it wait for report.students to be updated before Report.xls get downloaded?
Here is my code
`data service function
function getStudentsForExcel() {
var filter = studentFilter;
filter.data.perPage = StudentsModel.data.countTotal;
return $http.post(url + "/summeries", filter.data)
.then(onStudentSummeries)
.catch(onError);
function onStudentSummeries(response) {
return response.data;
}
}`
This function in my controller
`
function tocsv() {
studentData.getStudentsForExcel().then(function(data) {
report.students = data;
}).then(function() {
var blob = new Blob([document.getElementById('tableReport').innerHTML], {
type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8"
});
saveAs(blob, "Report.xls");
});
}`

is invoking a service into another service in angular

I need to save data and then I need to dispaly the changes immediately afterwards.
That's why I Have a
updateSaisine which allows me to update data
getOneSaisine which allows me get the data and display them:
Which is the more correct way and for which reasons ?
Should I write:
$scope.saveSaisine = function() {
saisineSrv.updateSaisine($scope.currentSaisine.idSaisine, $scope.currentSaisine).
then(
function() {
$scope.errorMessages = [];
if ($scope.currentSaisine.idMotif) {
toaster.pop('success', 'Réponse', 'Success');
angular.element('#modalSaisine').modal('hide');
saisineSrv.getOneSaisine($scope.currentSaisine.idSaisine, $scope.currentSaisine).then(function(response) {
$scope.currentSaisine.dateModif = response.dateModif;
});
},
function error(response) {
$scope.errorMessages = response.data;
toaster.pop('error', 'Réponse', 'We have a problem');
}
);
};
OR
$scope.saveSaisine = function() {
saisineSrv.updateSaisine($scope.currentSaisine.idSaisine, $scope.currentSaisine).
then(
function() {
$scope.errorMessages = [];
if ($scope.currentSaisine.idMotif) {
toaster.pop('success', 'Réponse', 'Success');
angular.element('#modalSaisine').modal('hide');
},
function error(response) {
$scope.errorMessages = response.data;
toaster.pop('error', 'Réponse', 'We have a problem');
}
);
saisineSrv.getOneSaisine($scope.currentSaisine.idSaisine, $scope.currentSaisine).then(function(response) {
$scope.currentSaisine.dateModif = response.dateModif;
});
};
the first option is a correct way how you should refresh your data because these services are asynchronous thus in the second example you may don't get fresh data (the getOneSaisine can finish before updateSaisine).

Resources