I am getting data back from a modal, I need to check the result and determine which outside function to fire based on many conditions.
I've verified that the data being passed back is formatted correctly and the series of else if's should be getting triggered, but it looks like it will skip over all conditions and do nothing.
What is the most productive way to go about implementing this logic?
My code:
dialogRef.afterClosed().subscribe(result => {
console.log('RESULT: ', result.delete);
if (result.isNew && !result.cancel) {
console.log('new story!');
this.boardService.updateTasks(this.job.id, [
...this.job.tasks,
result.task
]);
this.closeStories('update', this.job)
}
// means a delete has occured
else if (result.delete) {
this.closeStories('deleted triggered...')
// last story has been deleted, prompt newStory
if (this.stories.length < 2 && result === {}) {
console.log('Last story was deleted!');
this.closeStories('delete')
}
// a delete has happened
else if (this.stories.length > 1 && result === {}) {
console.log('A story was deleted!');
this.closeStories('deletedLast')
}
}
// means an update has occured
else if (result.id && !result.isNew) {
console.log('A story was Updated!');
const update = this.stories;
update.splice(result.index, 1, result.task);
this.boardService.updateTasks(this.job.id, update);
this.closeStories('update', this.job)
}
else if (result === undefined) {
return 0
}
// this.closedStoryListEmitter.emit(this.job);
console.log('hit close list event emitter!!');
});
//Have you checked other callbacks
dialogRef.afterClosed().subscribe(
result => {
console.log('RESULT: ', result.delete); //does this console.log executes?
//rest of the code
},
error=>{
//do something with and error
},
()=>{
//finished
}
);
I think if you want your if statements to be triggered, just do multiple if statements block without the else if block or at least that's how would I approach it.
...
if (result.isNew && !result.cancel) {
console.log('new story!');
this.boardService.updateTasks(this.job.id, [
...this.job.tasks,
result.task
]);
this.closeStories('update', this.job)
}
if (result.delete) {
this.closeStories('deleted triggered...')
// last story has been deleted, prompt newStory
if (this.stories.length < 2 && result === {}) {
console.log('Last story was deleted!');
this.closeStories('delete')
}
// a delete has happened
else if (this.stories.length > 1 && result === {}) {
console.log('A story was deleted!');
this.closeStories('deletedLast')
}
}
if (result.id && !result.isNew) {
console.log('A story was Updated!');
const update = this.stories;
update.splice(result.index, 1, result.task);
this.boardService.updateTasks(this.job.id, update);
this.closeStories('update', this.job)
}
if (result === undefined) {
return 0
}
...
Related
Is it possible to use if/else on firebase's realtime results? My database looks like this:
Previously I've tried it and it works if the result of both "waktu" is same, == recent.
but what I want is if one of the values "waktu" == recent, then "Hasil" = 0, if both of "time" nothing is equal to "Recent", then the value "Hasil" = 0.
if ("Recent" == (one of) "waktu") {
Hasil : "1";
} else {
Hasil : "0";
}
This is my code before, which value "Result" = 1, if both "waktu" values == recent. but i want if one values of "waktu" == Recent.
var recent = "";
var root = firebase.database().ref();
root.child("Time").on('value', (snapshot) => {
recent = snapshot.val().Recent;
});
root.child("jadwal-pakan").on('value', (snapshot) => {
snapshot.forEach(jadwal_waktu => {
if (jadwal_waktu.child("waktu").val() == recent) {
root.update({
Keadaan: {
Hasil: 1
}
});
} else {
root.update({
Keadaan: {
Hasil: 0
}
});
}
})
})
Thank you :)
The problem is in the timing of when the code executes. Since all data is loaded from Firebase asynchronously, your recent = snapshot.val().Recent may run after if (jadwal_waktu.child("waktu").val() == recent) { has run.
To ensure this is guaranteed, you'll need to nest the listeners like this:
root.child("Time").on('value', (snapshot) => {
recent = snapshot.val().Recent;
root.child("jadwal-pakan").on('value', (snapshot) => {
snapshot.forEach(jadwal_waktu => {
if (jadwal_waktu.child("waktu").val() == recent) {
root.update({
Keadaan: {
Hasil: 1
}
});
} else {
root.update({
Keadaan: {
Hasil: 0
}
});
}
})
})
});
Now there's no chance of the statements executing out of order, and the if (jadwal_waktu.child("waktu").val() == recent) { will work as expected.
I want to check whether the text element changes on x seconds and apply the for loop and conditional structure to verify if the change is applied. If the text is still not changed it will refresh the page and check again
Cypress.Commands.add('checkApprovedStatus', (targetData) =>{
cy.get('div[class^=ui-table-scrollable-body]').contains('tr', targetData).first().parent().within(function(){
cy.get('td').eq(10).children('span[class^=customer-badge]').then(($status) =>
{
//let currStatus = $status.text()
//cy.log(currStatus)
for(let count = 0; count <= 5; count++)
{
let currStatus = $status.text()
cy.log(currStatus)
if (currStatus === 'approved')
{
//if (currStatus.contains('Approved', {matchCase:false}))
//{
cy.log("End to end testing completed. All checks have passed!!")
break
//}
}
else
{
cy.reload()
cy.wait(5000)
$status.trigger('change')
}
}
})
})
})
For loops generally crash and burn in Cypress, but you can use a recursive function to simulate the loop.
When the loop (reload/trigger change) fails to find the status, throw an error to fail the test, or just return.
const checkApprovedStatus = (targetData, attempt = 0) => {
if (attempt === 5) {
// used up all attempts, can either fail the test
throw 'Was never approved'
// or just return without failing
return
}
cy.get('div[class^=ui-table-scrollable-body]')
.contains('tr', targetData).first().parent()
.within(() => {
cy.get('td').eq(10).children('span[class^=customer-badge]')
.then($status => {
if ($status.text() === 'approved') {
cy.log("All checks have passed!!")
} else {
cy.reload()
cy.wait(5000)
$status.trigger('change')
checkApprovedStatus(targetData, ++attempt)
}
})
})
})
So I'm trying to run a few checks inside a file. Lets say inside checks.js I have
module.exports = async (content) => {
// Check no.1
if (content.id != 'SomeID') return;
// Check no.2
if (content.length > 20) return;
//..etc
}
And in my main file I am requiring this file. I want it to return in the original file depending on the outcome of checks.js So lets say the content id isn't the same as 'SomeID', I want it to return and not to continue the rest of the code in my main file. I did require('filePath')(content) But it doesn't actually return in the main file as it should by instructions in checks.js What am I doing wrong and what should I be doing. Thank you in advance!
checks.js is returning an AsyncFunction, you must await it.
checks.js:
module.exports = async (content) => {
// Check no.1
if (content.id != 'SomeID') return;
// Check no.2
if (content.length > 20) return;
//..etc
return true // maybe your not returning truthy?
}
index.js:
const checks = require('./checks');
(async () => {
console.log('typeof checks()', typeof checks);
console.log('instance of', checks.constructor.name);
//
let content = {
id: 'SomeID'
};
if (await checks(content)) {
console.log('1. passed');
} else {
console.log('1. failed');
}
//
content = {
id: 'WrongID'
};
if (await checks(content)) {
console.log('2. passed');
} else {
console.log('2. failed');
}
})();
Will output when run:
typeof checks() function
instance of AsyncFunction
1. passed
2. failed
See Understanding async/await on NodeJS for more details.
I am using Google Cloud function to validate my OTP Authentication, and also using Firebase database to save code in the database.
My problem is, even when the If statements condition are satisfied, it always executes else statement. I am comparing code and codeValid from firebase database with the user input. Thus, my user input is satisfied with code and codevalid is also satisfied, but it always moves to else statement. I dont know why.
Here is my code
const admin = require('firebase-admin');
module.exports = function(req, res) {
if(!req.body.phone || !req.body.code) {
return res.status(422).send({error: 'Phone and Code Must be
Provided'});
}
const phone = String(req.body.phone).replace(/[^\d]/g, '');
const code = parseInt(req.body.code);
return admin.auth().getUser(phone)
.then(() => {
const ref = admin.database().ref('users/'+ phone);
return ref.on('value', snapshot => {
ref.off();
const user = snapshot.val();
if (user.code === code && user.codeValid === true) {
ref.update({ codeValid: false });
admin.auth().createCustomToken(phone)
.then(token => res.send({ token: token }))
.catch((err)=> res.status(422).send({ error:err }));
}
else {
return res.status(422).send({ error: 'Code Not Valid' });
}
});
})
.catch((err)=> res.status(422).send({ error:err }) )
}
So, I always get "code not valid" what ever the input i give. I cross checked all the values with firebase database also, everything matches. But couldn't find why its happening.
Add this above your if condition and check whether your statements are really true. I think it's possible that your datatypes are different for example for user.code and code. So you should also test it with == or with parsing your values.
// values and datatypes are equal
if (user.code === code) {
console.log('user.code === code');
}
// values and datatypes are equal
if (user.codeValid === true) {
console.log('user.codeValid === codeValid');
}
// values are equal
if (user.code == code) {
console.log('user.code == code');
}
// values are equal
if (user.codeValid == true) {
console.log('user.codeValid == codeValid');
}
For more information about the difference of == and === look at this answer:
Difference between == and === in JavaScript
I'd stuck with Rxjs operators.
This is a part of Angular's guard canActivate
const ifNoPatientCondition$ = this.dataService.getList().map(pl => {
console.log('im here'); // <<< this message not showing
const found = findOnlyAvailablePatients(pl);
if (found[0] === 1) {
this.stateService.patient.setCurrent(found[1]);
this.dataService.getPatientData(pid);
// return Observable.of(true);
return true;
} else {
if (found[0] === 0) {
this.stateService.app.message.send('Wrong patient status');
} else if (found[0] === -1) {
this.stateService.app.message.send('Wrong patient ID');
}
this.subscribes.forEach(subscribe => subscribe.unsubscribe());
this.stateService.navigate('/patients');
// return Observable.of(false);
// return false;
}
});
const warnOkCondition$ = this.stateService.patient.getCurrent().pipe(mergeMap(pat => {
if (!pat || pat.patient_id !== pid) { // <<< i'm interested with this condition
console.log('there is no patient!', pat); // <<< i see this message
return ifNoPatientCondition$; // <<< but cannot reach this line
} else {
if (pat.status === 'TREATMENT_COMPLETE') {
return Observable.of(false);
}
return Observable.of(true);
}
}));
return warningDialog().pipe(concatMap(warningResult => {
if (!warningResult) { // <<< if clicked No
this.stateService.navigate('/patients');
return Observable.of(false);
} else { // <<< 'Yes'
console.log('you are the best');
return warnOkCondition$;
}
}));
warningDialog() shows a dialog and returns observable of result.
If i clicked No, code works right: guard returns false and router navigate to /patients.
else if i clicked Yes, warnOkCondition$ works partially right (i'm interesting with first condition (with console.log)): i see message in console, but cannot reach next line - ifNoPatientCondition$ code.
Thanks!
Please use Types if you are working with Typescript. It is not clear what is an array and what is an Observable. Since warnOkCondition$ returns Observable.of(true/false) on some conditions, I assume this.dataService.getList() returns an Observable as well, and not a list, even though pl has no $-suffix at the end. In this case you need to subscribe to ifNoPatientCondition$ if you want it to be executed.
You might want to use switchMap or mergeMap here. https://netbasal.com/understanding-mergemap-and-switchmap-in-rxjs-13cf9c57c885