How to make a double GET on angular 1.x - angularjs

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;
}

Related

AngularJS check object/array is empty

I've read many questions and answers, noone has helped me. I've this function:
var model = {};
var mediaReproductionApp = angular.module("mediaReproductionApp",["ui.event",'ngAnimate']);
mediaReproductionApp.run(function ($http) {
$http.get("movimenti_per_totem.json").success(function (data) {
model.items = data;
});
});
mediaReproductionApp.controller("MediaReproductionCtrl", function($scope, $http, $timeout) {
$scope.item = model;
$scope.playVideo = function(media) {
return media ? "../gallery/video/" + media : null;
}
$scope.reproductionCodeIsEmpty = function() {
return Object.keys($scope.item).length == 0;
}
$scope.endVideo = function() {
$timeout(function() {
$http.get("php/delete_record.php").success(function () {
$http.get("movimenti_per_totem.json").success(function (data) {
$scope.item.items = data;
});
});
if($scope.reproductionCodeIsEmpty()) {
prelevaDati('../json/52.json', 'spot_creator', 'sc1', modello_SC, {});
$scope.checkMediaData();
}
},1800);
}
$scope.checkMediaData = function() {
$http.get("movimenti_per_totem.json").success(function (data) {
$scope.item.items = data;
});
if($scope.reproductionCodeIsEmpty()) {
$timeout(function(){$scope.checkMediaData();},2000);
}
}
$scope.checkMediaData();
});
This is my JSON file when it is not empty:
[ {"media":"zafferano_VP8.webm"}, {"media":"amaretti_VP8.webm"}, {"media":"passata_VP8.webm"}]
It never return true when it is empty. I've tried also:
$scope.reproductionCodeIsEmpty = function() {
return $scope.item.length == 0;
}
$scope.reproductionCodeIsEmpty = function() {
return $scope.item == {};
}
$scope.reproductionCodeIsEmpty = function() {
return angular.isUndefined($scope.item) || $scope.item === null;
}
$scope.reproductionCodeIsEmpty = function() {
return angular.isUndefined($scope.item.items) || $scope.item.items === null;
}
Nothing works... can u tell me why?
Thank you!
After you added to your question:
You define model as: model.items = data;
So, you empty model is: model = { items: [] }.
That's why it isn't empty. You need to test for model.items being empty.
If you need a tested way to tell that the object is empty, I'd recommend lodash.isEmpty(). You can use it for "any Array-like values such as arguments objects, arrays, buffers, strings, or jQuery-like collections".
https://lodash.com/docs/4.15.0#isEmpty
Since I don't know what your model is, this would cover the most possible data types.
_.isEmpty(null);
// => true
_.isEmpty(true);
// => true
_.isEmpty(1);
// => true
_.isEmpty([1, 2, 3]);
// => false
_.isEmpty({ 'a': 1 });
// => false
If you want to check if object/array is empty, I use:
angular.equals({}, yourObject);
angular.equals([], yourArray);

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);
};

Controller behavior(different data from Factory) which depends on view

This is the Factory.
angular
.module('WordsFactory', [])
.factory('WordsFactory', WordsFactory);
function WordsFactory($http) {
exports = {
basics1Data: null
};
exports.getWordsBasics1 = function () {
return $http.get('data/basics1.json')
.success(function (data) {
exports.basics1Data = data;
})
.error(function (data) {
console.log('There was an error!', data);
});
};
exports.getWordsBasics2 = function () {
return $http.get('data/basics2.json')
.success(function (data) {
exports.basics1Data = data;
})
.error(function (data) {
console.log('There was an error!', data);
});
};
return exports;
}
Controller:
angular
.module('app.words', ['WordsFactory'])
.controller('WordsController', WordsController);
function WordsController(WordsFactory) {
var vm = this;
WordsFactory.getWordsBasics1()
.then(core);
function core(res){
//json data binds to variable
vm.basics1Data = res.data;
vm.points = 0;
getRandom();
//check if words are correct
vm.wordCheck = function () {
if(vm.wordInput === vm.test) {
alert('good');
getRandom();
vm.points++;
} else {
alert('bad');
getRandom();
}
};
function getRandom() {
var random = Math.floor(Math.random() * 6);
vm.test = vm.basics1Data[random];
}
}
}
In this project I will have multiple views. Every view will have the same structure and gonna do the same thing.
Views are something like categories.
-cat1
-cat2
-cat3
-and so on...
Only thing that would be different is json file.
for ex.
cat1 will have cat1.json
cat2 cat2.json etc.
Controller gonna do the same operations in every view, only on different data. How can I achieve that without copy and paste methods in controller f.ex.
WordsFactory.getWordsBasics1...
WordsFactory.getWordsBasics2...
The code that I have works, but I want to avoid copy-paste things.
Thank you in advance for any help.

Angularjs/Ionic DB result with promise

I have a simple query that I am struggling with:
.factory('Config', function($http, DB) {
var self = this;
self.setValue = function(key,value) {
console.log('setValue(value)', value);
return DB.query("UPDATE config SET value = '"+value+"' WHERE key = '"+key+"'")
.then(function(result){
return DB.fetchAll(result);
});
}
self.getValue = function(key) {
return DB.query("SELECT value FROM config WHERE key = '"+key+"'")
.then(function(result){
return DB.fetchOne(result);
});
};
return self;
})
with the following code in controller.js under the heading:
.factory('DB', function($q, DB_CONFIG) {
var self = this;
self.db = null;
(I took the init part of the function away for the sake of simplicity. Also DB is working well when inserting, getting and updating data.)
self.fetchOne = function(result) {
var output = null;
output = angular.copy(result.rows.item(0));
return output;
};
self.query = function (sql, bindings) {
bindings = typeof bindings !== 'undefined' ? bindings : [];
var deferred = $q.defer();
self.db.transaction(function (transaction) {
transaction.executeSql(sql, bindings, function (transaction, result) {
deferred.resolve(result);
}, function (transaction, error) {
deferred.reject(error);
});
});
return deferred.promise;
};
self.fetchAll = function (result) {
var output = [];
for (var i = 0; i < result.rows.length; i++) {
output.push(result.rows.item(i));
}
return output;
};
Called like so:
$scope.config.recordar = Config.getValue("recordar");
Doing a console.log returns:
I am struggling to access the value: "true" which is highlighted in BLUE in the above image.
Any leads?
$scope.config.recordar = Config.getValue("recordar");
Does not work (ala JS). It has to be called like so:
Config.getValue("recordar").then(function(data) {
$scope.config.recordar
});
I assume that you shall change your function declaration from :
self.setValue = function(key,value) {
console.log('setValue(value)', value);
return DB.query("UPDATE config SET value = '"+value+"' WHERE key = '"+key+"'")
.then(function(result){
return DB.fetchAll(result);
});
}
to
self.setValue = function(key,value) {
console.log('setValue(value)', value);
DB.query("UPDATE config SET value = '"+value+"' WHERE key = '"+key+"'")
.then(function(result){
return DB.fetchAll(result);
});
}
You will return the result of your promise, not your promise
I have changed "return DB..." to "DB..."

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