I'm trying to make an input form that will check if the data exists in firebase database, below is the code that I used to check the data :
if(element.validation.codeunique) {
function checkCode(inputcode) {
firebaseUsers.orderByChild('code')
.equalTo(inputcode).once('value')
.then( snapshot => {
let thecode = null;
if(snapshot.val()){
thecode = false;
} else {
thecode = true;
}
console.log(thecode)
})
}
let checkcode = null;
checkcode = checkCode(element.value);
console.log(checkcode)
const valid = checkcode;
const message = `${!valid ? 'Code Exists':''}`;
error = !valid ? [valid,message] : error
}
in database i have a data :
users
-L3ZeHOI7XOmP9xhPkwX
-code:"DEM"
when I entered data DEM at the form :
console.log(thecode) result is false (which is the result that i want)
and when i entered another data ASD at the form :
console.log(thecode) result is true(which is the result that i want)
so the firebaseUsers actually is giving me the feedback/data that I want, but when I tried to get the data at valid with true/false,
this is the code that I originally used:
if(element.validation.codeunique) {
function checkCode(inputcode) {
firebaseUsers.orderByChild('code')
.equalTo(inputcode).once('value')
.then( snapshot => {
if(snapshot.val()){
return false;
} else {
return true;
}
})
}
const valid = checkCode(element.value);
const message = `${!valid ? 'Code Exists':''}`;
error = !valid ? [valid,message] : error
}
the valid shows = undefined,
my goal is to make the valid shows true/false,
could someone help me, and point out, what did i do wrong?
*I make the first code just to point out that the firebase is actually working
*the second code is the one that I originally used
There are a few issues that are standing out to me.
First, the code that you use originally was using return inside of the function's if / else conditional. I believe this is correct, you'll want to go back to doing that.
Second, the firebase.orderByChild() function that you are calling is a Promise as it has a .then() statement appended to it. What this means is that the function does not synchronously finish executing and return a value. The code below that promise is being run while the firebase function is still processing.
Give this a shot and see if it works, and if you have any further errors beyond the promise.
if(element.validation.codeunique) {
function checkCode(inputcode) {
firebaseUsers.orderByChild('code')
.equalTo(inputcode).once('value')
.then( snapshot => {
if(snapshot.val()){
return false;
} else {
return true;
}
console.log(thecode)
})
}
let message = checkCode(element.value) ? 'Code Exists':'Code Does not Exist';
}
I've done it outside of the function above and by checking it when the user submit the form, and if the code exists, i direct it to form again :
firebaseUsers.orderByChild('code')
.equalTo(mycode)
.once('value')
.then (snapshot => {
if(snapshot.val()) {
alert("Code Exists, Please Choose another");
this.props.history.push('/myscreen')
} else {
//submit the data
}
hopefully this will help someone
Related
I have a problem changing a data parameter in my component file:
this.commandList.ListesCommandesATransmettre.forEach(data => {
this.catalogs.forEach(catalog => {
if (catalog.Libelle === data.Catalogue) {
if (catalog.selected === false) {
console.log(data.isSelected)
data.isSelected = false;
console.log(data.isSelected)
console.log(data);
}
}
})
});
This code displays:
true
false
But the value of isSelected in console.log(data) is still true. So, why is the result false?
Try this if it's a loop problem with the callback
for (let data of this.commandList.ListesCommandesATransmettre) {
for (let catalog of this.catalogs) {
if (catalog.Libelle === data.Catalogue) {
if (catalog.selected === false) {
console.log(data.isSelected)
data.isSelected = false;
console.log(data.isSelected)
console.log(data);
}
}
}
}
I cant understand logic of your code. What happen if this.catalogs has many catalogs that meet the condition? isSelected will be setted many times in false.
Maybe this works (if I understand your logic):
this.commandList.ListesCommandesATransmettre = this.commandList.ListesCommandesATransmettre.map(data => {
const mutateData = Object.assign({}, data);
// If condition math, then isSelected set in false. Else, isSelected keep the his value
mutateData.isSelected =
this.catalogs.some(catalog => catalog.Libelle === data.Catalogue && !catalog.selected) ? false : mutateData.isSelected;
return mutateData;
})
Try this code to test if it is updating correctly. the loop will tell which are true/false and you can see if that is the case in the updated data.
this.commandList.ListesCommandesATransmettre.forEach((data, index) => {
this.catalogs.forEach(catalog => {
if (catalog.Libelle === data.Catalogue) {
if (catalog.selected === false) {
data.isSelected = false;
}
console.log(index + 'is selected: ' + data.isSelected)
}
})
});
console.log(this.commandlist);
Something I have noticed is that web browsers will only keep the the 'most current' reference of an object in memory. So after a loop has ended, the 'most current' reference is the last one to fire. So you may be looking at your last object and not the one you are trying to test. If someone else knows more, or has a reference to what is actually happening, please edit this post.
I have two tabs in my admin interface. I am storing the response in my session storage. When I do the updation of any records in the tab or if I insert new record also, the same thing should be reflected in the storage also. But currently, the changes are not getting reflected in the storage. I tried my best to sort out, but I could not able to succeed. Any help/advice greatly appreciated.
Angularjs:
$scope.Pool = [];
if (!localStorageService.get('Pool')) {
Role.getPool().success(function(data) {
if (data.responseCode === 0) {
_.forEach(data.response.demoPool, function(value, key) {
dataObj = {};
dataObj.id = value.poolId;
dataObj.value = value.poolName;
$scope.Pool.push(dataObj);
});
localStorageService.set('Pool', $scope.Pool);
} else {
$scope.alerts.alert = true;
$scope.alerts.type = 'danger';
$scope.alerts.msg = data.errorMsg;
}
})
First time it will do because !localStorageService.get('Pool') becomes true. But next time it will return false because storage has value already, it will not get inside the if condition. so to resolve this remove the session storage 'Pool' to allow to execute your Role.getPool().success(function(data) {
if (!sessionStorage.length) {
// Ask other tabs for session storage
localStorage.setItem('getSessionStorage', Date.now());
};
window.addEventListener('storage', function (event) {
switch (event.key) {
case 'getSessionStorage':
// Some tab asked for the sessionStorage -> send it
localStorage.setItem('sessionStorage', JSON.stringify(sessionStorage));
localStorage.removeItem('sessionStorage');
break;
case 'sessionStorage':
// sessionStorage is empty -> fill it
var data = JSON.parse(event.newValue);
for (key in data) {
sessionStorage.setItem(key, data[key]);
}
break;
}
});
I am unable to do the promise looping.
I make a service call to get list of providers, then for each provider, I make another service call to get a customer.
A provider has 1 or more customers. So eventual list of customer is to be decorated and displayed.
In other format I am trying to achieve:
*serviceA.getProvider(){
foreach(providers){
foreach(provider.customerID){
serviceB.getCustomer(customerId)
}
}
}
.then(
foreach(Customer){
updateTheCustomer;
addUpdatedCustomerToAList
}
displayUpdatedCustomreList();
)*
I have written following code, that isn't working
doTheJob(model: Object) {
let A = [];
let B = [];
let fetchP = function(obj) {
obj.Service1.fetchAllP().then(function (response) {
let P = cloneDeep(response.data);
_.forEach(P, function(prov) {
_.forEach(prov.CIds, function(Id) {
A.push(Id);
});
});
_.forEach(A, function(CId) {
return obj.Service2.getById(CId);//what works is if this statement was: return obj.Service2.getById(A[0]);
//So, clearly, returning promise inside loop isn't working
});
})
.then(function(response) {
B.push(response.data); //This response is undefined
angular.forEach(B, function (value) {
obj.updateAdr(value)
});
obj.dispay(B);
});
};
fetchP(this);
}
forEach don't stop when you use return inside of it, try to use a plain loop instead, why you don't just loop with for ?
_.forEach(A, function(CId) {
return obj.Service2.getById(CId);
}
as stated by #Ze Rubeus if you return inside a callback within a for loop that value will be lost, since it's not returned to the caller.
probably you wanted something like this
return Promise.all(A.map(function(CId){
//collect each promise inside an array that will then be resolved
return obj.Service2.getById(CId);
})
I´m fairly new to angular 2 and i have a little Problem and I didn´t find another thread which really descriebs my problem and has a solution for this...
To start with, i have a service, which manages data (epgService).
I have a second service, which loads data from database (apiService) and returns data as Observable.
And I have a component, whicht wants data.
Now the component asks the epgService (service 1) to get some data.
Then the epgService checks, if the data is actually loaded from server and is "cached" internally. It it is not, it asks the apiService to load the data.
My Problem: I do not know, how i can return an Observable from epgService to the component.
In the epgService i a a variable to store the data. If the data is there, the variable get filled. If not, the data is loaded from apiService as Observable, then the data of the observable stored in the local variable.
Afterwards, at the end of the service, i want to return the local variable as Observable.
How can i do this?
Here´s the code:
epgService:
getEPGbyChannel(channelID, mydate) {
let epg: EPG = this.variables.getEPG();
// local variable to store the data which then should be returned
let returnEPG;
// check if epg is there
for (let channel of epg.epg) {
if (channel.channelId === channelID) {
for (let date of channel.dates) {
if (date === mydate) {
console.log("yeah, epg is there :)");
// return EPG
returnEPG = date;
return returnEPG.asObservable();
}
}
}
}
// load epg from database, because its not there
if (!returnEPG) {
console.log("epg is not there :(");
let fromDate = new Date(mydate.getFullYear(), mydate.getMonth(), mydate.getDate(), 0, 0, 0);
let endDate = new Date(mydate.getFullYear(), mydate.getMonth(), mydate.getDate(), 23, 59, 59);
this.apiService.getChannelEPGbyTime(channelID, fromDate, endDate).
subscribe(
data => {
if (data.programme) {
console.log("got epg:");
console.log(data.programme);
// write data from observable in local variable
returnEPG = this.formatter.formatChannelEPG(data.programme);
return returnEPG.asObservable();
} else {
console.log("epg doesn´t exist on server");
returnEPG = "no epg";
return returnEPG.asObservable();
}
});
}
}
Component:
this.epgService.getEPGbyChannel(channel.EPGID, date).
subscribe(
data => {
console.log("data!!!");
console.log(data);
},
//error => this.error = <any>error,
error => {
this.variables.setFailure("Das EPG konnte nicht geladen werden.");
this.loading = false;
});
The return value here is 'returnEPG is undefined'.
Can someone provide me a solution?
Thanks so much!
Codeflow is-
I am checking if an entry called listobject exists in the AsyncStorage.
If it doesn't exist, then, I create an object, add few attributes and set the store. I get the store to obj as I have to compare in the next if condition.
If the listobject entry already exists(2nd time), then, it directly comes to the 2nd block, and compares. (The reason I get values to obj in 1st step is because I can have a common obj.data.isdirty condition.
Here is my code-
AsyncStorage.getItem('listobject').then((obj) => {
if(obj == undefined)
{
var obj1 ={};
obj1.data ={};
obj1.data.isdirty = true;
console.log("obj1 = "+ JSON.stringify(obj1));
AsyncStorage.setItem('listobject',obj1);
obj = AsyncStorage.getItem('listobject');
console.log("obj = "+ JSON.stringify(obj));
}
if(obj.data.isdirty)
{
obj.data.isdirty = false;
AsyncStorage.setItem('listobject',JSON.stringify(obj));
return AsyncStorage.getItem('listobject');
}
}).done();
I have 2 questions which are the outcome of the same issue-
Logs. I am setting obj1 and getting the same value for obj (so that I can compare the next if condition). Why am I not able to get the same value that I have set?
12-03 00:27:56.281 32598-487/com.abc D/ReactNativeJS: 'obj1 = {"data":{"isdirty":true}}'
12-03 00:27:56.286 32598-487/com.abc D/ReactNativeJS: 'obj = {"_37":0,"_12":null,"_59":[]}'
This is the end result of the above logs. I am getting that list.data.isdirty is undefined. I guess that because the JSON format I am accessing does not exist in obj i.e., obj.data.isdirty doesn't exist. So, how do I overcome this?
undefined is not an object (evaluating 'list.data.isdirty');
Please tell me what am I doing wrong?
I actually copied the object from one to another. It worked.
AsyncStorage.getItem('listobject').then((obj) => {
if(obj == undefined)
{
var obj1 ={};
obj1.data ={};
obj1.data.isdirty = true;
console.log("obj1 = "+ JSON.stringify(obj1));
AsyncStorage.setItem('listobject',obj1);
obj = obj1; //THIS IS WHAT I DID!
console.log("obj = "+ JSON.stringify(obj));
}
if(obj.data.isdirty)
{
obj.data.isdirty = false;
AsyncStorage.setItem('listobject',JSON.stringify(obj));
return AsyncStorage.getItem('listobject');
}
}).done();
I'm not quite following the entire question I do however see an issue with the use AsyncStorage. Going by the name, Async implies that the operations are asynchronous. So when you do getItem(key), you should either pass in a callback or use the Promise object it returns as you are doing in the first line of code.
obj = AsyncStorage.getItem('listobject');
console.log("obj = "+ JSON.stringify(obj));
obj is going to be the Promise in this case.
Then if you check on obj for the presence of a data and isDirty child property, they will not exist on the Promise.
Sometimes while doing console.log(AsyncStorage.getItem('Soomekey')) you will be getting undefined as you can't directly pull values from the AsyncStorage as returns a promise so what you should be writing is
const SomeFunction = async () => {
try {
const value = await AsyncStorage.getItem('somekey');
console.log(value);
} catch (err) {
console.log(err);
}
}