A function does not wait for another function to execute - angularjs

This is my service
var validateEmailService=function (validateEmailUrl,validateEmailParameters,email) {
var url=validateEmailUrl +'?';
angular.forEach(validateEmailParameters,function (value,key) {
url=url +key +'='+ value.parameter +'&';
});
url=url+'email='+email;
$http.get(url).then(function (value) {
var result = value;
var smtpCheck = result.data.smtp_check;
var mxRecordsCheck = result.data.mx_found;
// console.log(smtpCheck ,mxRecordsCheck);
if (smtpCheck === true && mxRecordsCheck === true){
//console.log('In');
return true;
}
//console.log('Out');
});
};
var sendEmailService=function (sendEmailApiUrl,emailData,config,email,firstName,lastName) {
emailData = JSON.stringify(emailData);
emailData = emailData.replace("%%Email%%", email);
emailData = emailData.replace("%%FirstName%%", firstName);
emailData = emailData.replace("%%LastName%%", lastName);
emailData = JSON.parse(emailData);
$http.post(sendEmailApiUrl, emailData, config);
};
return {
validateEmailService: validateEmailService,
sendEmailService: sendEmailService
};
And I have called these functions here in the controller
var validate = emailService.validateEmailService(validateEmailUrl, validateEmailParameters,$scope.patient.Email);
if (validate === true) {
emailService.sendEmailService(sendEmailApiUrl, emailData, config,$scope.patient.Email,$scope.patient.givenName,$scope.patient.familyName);
messagingService.showMessage("info", "REGISTRATION_LABEL_SAVED");
$state.go("patient.edit", {
patientUuid: $scope.patient.uuid
});
}
else {
alert('Email does not exist');
}
So when the if statement is executed validate does not contain anything and it automatically goes to the else part even when validate should be true.

You should use the promise instead, the $http.get is asynchronous
var validateEmailService=function (validateEmailUrl,validateEmailParameters,email) {
var url=validateEmailUrl +'?';
angular.forEach(validateEmailParameters,function (value,key) {
url=url +key +'='+ value.parameter +'&';
});
url=url+'email='+email;
// IMPORTANT PART: USE RETURN
return $http.get(url).then(function (value) {
var result = value;
var smtpCheck = result.data.smtp_check;
var mxRecordsCheck = result.data.mx_found;
// console.log(smtpCheck ,mxRecordsCheck);
if (smtpCheck === true && mxRecordsCheck === true){
//console.log('In');
return true;
}
//console.log('Out');
});
};
And then in your controller:
emailService.validateEmailService(validateEmailUrl, validateEmailParameters,$scope.patient.Email).then(function(validate){
if (validate === true) {
emailService.sendEmailService(sendEmailApiUrl, emailData, config,$scope.patient.Email,$scope.patient.givenName,$scope.patient.familyName);
messagingService.showMessage("info", "REGISTRATION_LABEL_SAVED");
$state.go("patient.edit", {
patientUuid: $scope.patient.uuid
});
} else {
alert('Email does not exist');
}
})
Also, see this link about promises

Related

NodeJs note app delete function is not working?

I am building a Nodejs Note app and I am very new at this, so here the delete function doesn't work it, deletes everything from the array and I want to delete only title
There are two file app.js and note.js.
Here's the content of app.js file
if (command === "add") {
var note = notes.addNote(argv.title, argv.body);
if (note) {
console.log("Note created");
console.log("__");
console.log(`Title: ${note.title}`);
console.log(`Body: ${note.body}`);
} else {
console.log("The title has already exist")
}
} else if (command === "delete") {
var noteRemoved = notes.delNote(argv.title)
var message = noteRemoved ? "Note has been removed" : "Note not found";
console.log(message)
}
Here's the note.js content
var fetchNotes = function () {
try {
var noteString = fs.readFileSync("notes-data.json")
return JSON.parse(noteString);
} catch (e) {
return [];
}
};
var saveNotes = function (notes) {
fs.writeFileSync("notes-data.json", JSON.stringify(notes));
};
var addNote = function (title, body) {
var notes = fetchNotes();
var note = {
title,
body
};
var duplicateNotes = notes.filter(function (note) {
return note.title === title;
});
if (duplicateNotes.length === 0) {
notes.push(note);
saveNotes(notes);
return note;
};
}
var delNote = function (title) {
var notes = fetchNotes();
var filteredNotes = notes.filter(function (note) {
note.title !== title;
});
saveNotes(filteredNotes);
return notes.length !== filteredNotes.length
}
You miss return statement in delNote filter function
var filteredNotes = notes.filter(function (note) {
return note.title !== title;
});
or we can use es6 syntax:
const filteredNotes = notes.filter(note => note.title !== title);
You need to add return note.title !== title; in delNote function.

Angularsjs cannot find service function

My filterProducts function makes a call to findIntersection which is present but I get an error findIntersection is undefined.
angular.module('BrandService', [])
.service('BrandService', function ($filter, DataService) {
var productDb;
var products;
return {
filterProducts(brands, priceRange) {
var filteredProducts = [];
var brandProducts = [];
var priceProducts = [];
var productsArray = [];
var brandChecked = false;
var priceChecked = false;
angular.forEach(brands, function (brand) {
if (brand.checked) {
brandChecked = true;
angular.extend(brandProducts,
$filter('filter')(productDb, { 'brand': brand.name }));
}
if (brandChecked) {
productsArray.push(brandProducts);
console.log('brandProducts = ', brandProducts)
}
});
angular.forEach(priceRange, function (price) {
if (price.checked) {
priceChecked = true;
let filteredProductDb = productDb.filter((prod) => {
return (prod.price >= price.low && prod.price <= price.high);
});
angular.extend(priceProducts, filteredProductDb);
}
});
if (priceChecked) {
productsArray.push(priceProducts);
// console.log('priceProducts = ', priceProducts)
}
if (!brandChecked && !priceChecked) {
filteredProducts = products;
} else {
if (productsArray.length > 1) {
filteredProducts = findIntersection(productsArray);
} else {
filteredProducts = productsArray[0];
}
}
return filteredProducts;
},
findIntersection(productsArray) {
console.log('findIntersection called')
var filteredProducts = [];
var filteredSet = new Set();
for(var i=0; i < productsArray.length - 1; i++) {
var products1 = productsArray[i];
var products2 = productsArray[i+1];
angular.forEach(products1, function(product1) {
angular.forEach(products2, function(product2) {
if(product1._id == product2._id) {
filteredSet.add(product1);
}
});
});
}
filteredProducts = Array.from(filteredSet);
return filteredProducts;
}
}
})
My filterProducts function makes a call to findIntersection which is present but I get an error findIntersection is undefined.
My filterProducts function makes a call to findIntersection which is present but I get an error findIntersection is undefined.
You are returning a javascript object with properties. You are not defining global functions.
You need to store the service returned before :
var service = { findProducts: ... , findIntersection: ... };
return service;
And instead of calling findIntersection, call service.findIntersection.
You have to make a reference to local object.
Simply change this: filteredProducts = findIntersection(productsArray);
to this: filteredProducts = this.findIntersection(productsArray);

Refresh multiple pages in a controller

I would like to know if it was possible to update several pages in a single controller?
I need to refresh my home page after adding data to my list.
For now I use a pull to refresh in my homepage, but I would like it to update after an addition in my list.
my controller :
.controller('addCRCtrl', function ($scope, $state, $stateParams, $ionicPopup, $ionicLoading, $timeout, AppService) {
let loadData = () => {
$ionicLoading.show();
$scope.loading=true;
$scope.form = {};
$scope.formProjet = {};
$scope.form.patient = idjeune;
$scope.form.dateVisite = new Date();
AppService.patient(idjeune).then(function (response) {
$scope.patient = response;
console.log(response);
});
AppService.user().then(function (response) {
$scope.bene1 = response;
console.log(response);
});
AppService.hopitaux().then(function (response) {
$scope.hopitaux = response;
});
AppService.lieuxlist().then(function (response) {
$scope.lieux = response;
});
AppService.userByAntenneAddCR().then(function (response) {
console.log(response);
$scope.listeBene = JSON.parse(JSON.stringify(response));
});
AppService.typeVisite().then(function (response) {
$scope.listeVisite = JSON.parse(JSON.stringify(response));
});
AppService.projet(idjeune).then(function (response) {
$scope.projets = response;
});
AppService.getCategorie().then(function (response) {
$scope.categorieprojet = response;
console.log(response);
if (update) {
$scope.updating = update;
$scope.form.dateVisite = new Date(cr.date);
for (let i in $scope.lieux) {
if ($scope.lieux[i].id == cr.idLieu) {
$scope.lieu = $scope.lieux[i];
break;
}
}
$scope.form.lieudetail = cr.lieudetail;
$scope.bene1 = {
id: cr.bene1,
nom: cr.benevole1
}
$scope.bene2 = {
id: cr.bene2,
nom: cr.benevole2
}
$scope.bene3 = {
id: cr.bene3,
nom: cr.benevole3
}
console.log("Benevole 1 : ", $scope.bene1);
console.log("Benevole 2 : ", $scope.bene2);
console.log("Benevole 3 : ", $scope.bene3);
$scope.form.description = cr.compteRenduVisite;
$scope.form.todo = cr.todo;
$scope.form.etatpatient = cr.etatPatient;
for (let i in $scope.listeVisite) {
if ($scope.listeVisite[i].id == cr.typeVisite) {
$scope.typeVisite = $scope.listeVisite[i];
break;
}
}
for (let i in $scope.projets) {
if ($scope.projets[i].id == cr.idProjet) {
$scope.projet = $scope.projets[i];
break;
}
}
$timeout(() => { $ionicLoading.hide(); $scope.loading=false;;}, 6000);
}
else
$timeout(() => { $ionicLoading.hide(); $scope.loading=false;}, 2000);
});
}
$scope.$on('$ionicView.beforeEnter', function (event, viewData) {
loadData();
});
$scope.addCr = function () {
$ionicLoading.show();
let isValid = $scope.form.dateVisite && $scope.patient && $scope.bene1 && $scope.form.description && $scope.form.todo;
isValid = isValid && $scope.form.etatpatient && $scope.typeVisite;
let formInvalid = () => {
$ionicLoading.hide();
var alertPopup = $ionicPopup.alert({
template: '<p style="text-align: center;">Veuillez renseigner tous les champs</p>'
});
}
if (!isValid) {
formInvalid();
return;
}
$scope.form.lieu = ($scope.lieu)? $scope.lieu.id:0;
$scope.form.bene1 = $scope.bene1.id;
$scope.form.bene2 = ($scope.bene2) ? $scope.bene2.id : null;
$scope.form.bene3 = ($scope.bene3) ? $scope.bene3.id : null;
$scope.form.lieudetail = ($scope.form.lieudetail) ? $scope.form.lieudetail : "-";
let temp = $scope.form.dateVisite;
//$scope.form.dateVisite = $scope.form.dateVisite.toISOString().slice(0, 10);
let newProject = false;
$scope.form.typeVisite = $scope.typeVisite.id;
switch ($scope.typeVisite.id) {
case 3:
newProject = true;
isValid = isValid && $scope.cprojet && $scope.formProjet.description && $scope.formProjet.titre;
break;
case 4:
case 5:
if ($scope.projet) $scope.form.projet = $scope.projet.id;
isValid = isValid && $scope.projet;
break;
default:
$scope.form.projet = 0;
break;
}
for (var i in $scope.hopitaux) {
if ($scope.hopitaux[i].nom === $scope.patient.hopital) {
$scope.form.hopital = $scope.hopitaux[i].id;
}
}
for (var j in $scope.form) {
if ($scope.form[j] == null) {
if (j == 'bene2' || j == 'bene3')
$scope.form[j] = 0;
else
delete $scope.form[j];
}
}
if (!isValid) {
formInvalid();
return;
}
let callService = () => {
var myform = angular.copy($scope.form);
if (update)
myform.dateVisite = new Date($scope.form.dateVisite.getTime() + 86400000).toISOString().slice(0, 10);
else
myform.dateVisite = $scope.form.dateVisite.toISOString().slice(0, 10);
console.log(myform);
let idtogo = (update) ? cr.id : null;
AppService.addCR(myform, idtogo).then(function (response) {
update = false;
cr = null;
var alertPopup = $ionicPopup.alert({
title: 'Ajout Réussie !',
template: '<p style="text-align: center;">Merci d\'avoir renseigné les informations relatives à la visite !</p>'
});
$scope.form.dateVisite = temp;
console.log(response);
$ionicLoading.hide();
$state.reload('menu.ficheJeune');
$state.go('menu.ficheJeune');
});
}
if (!newProject || update)
callService();
else {
$scope.formProjet.categorie = $scope.cprojet.id;
$scope.formProjet.patient = idjeune;
var myprojectform = angular.copy($scope.formProjet);
console.log(myprojectform);
AppService.addProject(myprojectform).then((response) => {
console.log(response);
if (response) {
AppService.projet(idjeune).then(function (response) {
for (let i in response) {
console.log("Response :", response);
let temp = false;
for (let j in $scope.projets) {
if (response[i].id == $scope.projets[j].id) {
temp = true;
}
}
if (!temp) {
$scope.form.projet = response[i].id;
callService();
break;
}
}
});
}
});
}
};
AppService.refreshToken().then(function (response) {
if ($scope.token) {
console.info('Refresh');
}
});
})
For now, to update my first page I do:
$state.reload('menu.ficheJeune');
$state.go('menu.ficheJeune');
But I would also like to update a second page called 'menu.home'.
I thank you in advance
You can use this in your homeCtrl :
$scope.$on('$ionicView.beforeEnter', function() {
console.log('beforeEnter');
// your code
});

jhipster principal.service.js not working correct for hasAuthority. Need to disable menus based

We are using jHipster. I am new to this.
When trying to access another method hasPermission, it is always returning false before and hence we are unable to disable the menu. In authority, we are passing values like 'Company' and this checks internally with a userPermission Object to see if the user has 'Read' access. The user does have the access, but the code always returns false and hence the menu is always disabled. Am I making something wrong here ? Here is the complete code
(function() {
'use strict';
angular
.module('icmApp')
.factory('Principal', Principal);
Principal.$inject = ['$q', 'Account'];
function Principal ($q, Account) {
var _identity,
_authenticated = false;
var _authenticated = false;
var service = {
authenticate: authenticate,
hasAnyAuthority: hasAnyAuthority,
hasAuthority: hasAuthority,
identity: identity,
isAuthenticated: isAuthenticated,
isIdentityResolved: isIdentityResolved,
hasPermission: hasPermission
};
return service;
function authenticate (identity) {
_identity = identity;
_authenticated = identity !== null;
}
function hasAnyAuthority (authorities) {
if (!_authenticated || !_identity || !_identity.authorities) {
return false;
}
for (var i = 0; i < authorities.length; i++) {
if (_identity.authorities.indexOf(authorities[i]) !== -1) {
return true;
}
}
return false;
}
function hasAuthority (authority) {
if (!_authenticated) {
return $q.when(false);
}
var bPerm= hasPermission(authority);
if(bPerm==true)
{
alert("Permission is available");
return true;
}else
{
alert("Permission is NOT available");
return false;
}
/*return then(function(_id) {
return _id.authorities && _id.authorities.indexOf(authority) !== -1;
},function(){
return false;
});*/
}
function identity (force) {
var deferred = $q.defer();
if (force === true) {
_identity = undefined;
}
// check and see if we have retrieved the identity data from the server.
// if we have, reuse it by immediately resolving
if (angular.isDefined(_identity)) {
deferred.resolve(_identity);
return deferred.promise;
}
// retrieve the identity data from the server, update the identity object, and then resolve.
Account.get().$promise
.then(getAccountThen)
.catch(getAccountCatch);
return deferred.promise;
function getAccountThen (account) {
_identity = account.data;
_authenticated = true;
deferred.resolve(_identity);
}
function getAccountCatch () {
_identity = null;
_authenticated = false;
deferred.resolve(_identity);
}
}
function isAuthenticated () {
return _authenticated;
}
function isIdentityResolved () {
return angular.isDefined(_identity);
}
function hasPermission(authority){
var userPermission;
var bPermission=false;
//alert("Calling has Permission");
Account.getAllPermissions(function onSuccess(data) {
userPermission=data;
if(userPermission){
//alert("User Permission is "+ userPermission);
for(var i=0; i< userPermission.length; i++)
{
if((userPermission[i].object_name==authority)&& ((userPermission[i].read_access==true) || (userPermission[i].create_access==true)) )
{
bPermission= true;
break;
}
}
}
});
return bPermission;
}
}
})();

Cordova.writefile function doesn't run, but doesn't give an error

I'm making an ionic application. I have a function called scope.win() that's supposed to fire when a quiz is finished, and then update the JSON file to add that quiz to the number of finished quizzes but it doesn't run properly.It doesn't give off any error. The function just stops running at a certain point and the app keeps going and nothing is happening.
This is the controller's file
angular.module('controllers', ['services'])
.controller('MainCtrl', function ($scope, $state, data) {
$scope.$on('$ionicView.enter', function () {
data.create();
});
$scope.chapter = data.chapterProgress();
})
.controller("BtnClick", function ($scope, lives, data, $cordovaFile, $ionicScrollDelegate) {
var live = 3;
var clickedOn = [];
var numQuestions;
$scope.part2Cred = false;
$scope.part3Cred = false;
$scope.part4Cred = false;
$scope.part5Cred = false;
$scope.part6Cred = false;
$scope.part7Cred = false;
$scope.part8Cred = false;
$scope.part9Cred = false;
$scope.part10Cred = false;
$scope.partQCred = false;
$scope.setNumQuestions = function(num){
numQuestions = num;
}
$scope.updatelives = function (){
//grabs the element that is called liv then updates it
var livesOnPage = document.getElementById('liv');
livesOnPage.innerHTML = live;
}
$scope.wrong = function (event){
var selec = document.getElementById(event.target.id);
if(clickedOn.includes(selec)){}
else{
selec.style.color = "grey";
clickedOn.push(selec);
live = live - 1;
if(live == 0){
$scope.gameover();
}
else{
$scope.updatelives();
}
}
}
$scope.right = function (event,chapter, section){
var selec = document.getElementById(event.target.id);
if(clickedOn.includes(selec)){}
else{
selec.style.color = "green";
clickedOn.push(selec);
numQuestions = numQuestions - 1;
if(numQuestions === 0){
$scope.win(chapter, section);
}
}
}
$scope.gameover = function(){
alert("game over please try again");
live = 3;
$ionicScrollDelegate.scrollTop();
$scope.partQCred = false;
$scope.part1Cred = !$scope.part1Cred;
for(i = 0; i< clickedOn.length;i++){
clickedOn[i].style.color = "rgb(68,68,68)";
}
}
$scope.win = function (chapter, section) {
alert("Well Done");
var data = data.chapterProgress(); // It is at this point that the //function stops running without giving off any error.
alert("Good Job");
var sectionsComplete = data[chapter].sectionsCompleted;
var totalsection = data[chapter].totalSections;
if (section === totalSection) {
window.location.href = "#/chapter1sections";
return;
}
if (section > sectionsComplete) {
data[chapter].sectionsCompleted += 1;
var url = "";
if (ionic.Platform.isAndroid()) {
url = "/android_asset/www/";
}
document.addEventListener('deviceready', function () {
$cordovaFile.writeFile(url + "js/", "chapters.json", data, true)
.then(function (success) {
// success
alert("Json file updated")
window.location.href = "#/chapter1sections";
}, function (error) {
// error
});
});
}
}
});
Here is the Services file. It seems to run fine but it is referenced a lot in the problematic sections of code in the controllers so I figured it was necessary to put it here.
angular.module('services', [])
.service('lives', function () {
var live = 3;
return {
getlives: function () {
return live;
},
setlives: function (value) {
live = value;
}
};
})
.service('data', function ($cordovaFile, $http) {
var url = "";
if (ionic.Platform.isAndroid()) {
url = "/android_asset/www/";
}
return {
//Run this function on startup to check if the chapters.json file exists, if not, then it will be created
create: function () {
var init = {
"one": {
"sectionsCompleted": 0,
"totalSections": 4
},
"two": {
"sectionsCompleted": 0,
"totalSections": 1
}
};
$cordovaFile.writeFile(url + "js/", "chapters.json", init, false)
.then(function (success) {
// success
}, function (error) {
// error
});
},
chapterProgress: function () {
return $http.get(url + "js/chapters.json").success(function (response) {
var json = JSON.parse(response);
return json;
}, function (error) {
alert(error);
});
}
}
});
Thank You so much for the help and time.

Resources