Nativescript angular using dialog confirm - dialog

I have a utils class which contains the showMsg function to use the ui/dialogs
showMsg(titleTxt: string, msg: string, btnTxt: string, type: string){
switch(type){
case 'confirm':
dialogs.confirm({
title: titleTxt,
message: msg,
okButtonText: btnTxt,
cancelButtonText: 'No'
}).then((result) => {
console.log(titleTxt + " Dialog closed!" + result);
return result;
});
break;
default:
dialogs.alert({
title: titleTxt,
message: msg,
okButtonText: btnTxt
}).then(() => {
console.log(titleTxt + " Dialog closed!");
return true;
});
}
}
The problem is when I call this function from another component for a confirm dialog, the component doesn't wait for the result from the dialog box before continuing. I want it to conditionally continue based on the user response.
edit:
The new showMsg function
showMsg(titleTxt: string, msg: string, btnTxt: string, type: string){
switch(type.toLowerCase()){
case 'confirm':
return dialogs.confirm({
title: titleTxt,
message: msg,
okButtonText: btnTxt,
cancelButtonText: 'No'
}).then((result) => {
console.log(titleTxt + " Dialog closed!" + result);
return result;
});
default:
return dialogs.alert({
title: titleTxt,
message: msg,
okButtonText: btnTxt
}).then(() => {
console.log(titleTxt + " Dialog closed!");
return true;
});
}
}
The call to the showMsg function is now this
this.myutil.showMsg('Update Cleaning Status', 'Are you Sure?', 'Yes', 'Confirm').then((result)=> {
console.log('In then: ' + result);
alert(result);
});
Unfortunately we can't have any code after the call to the function as it get executed before what happens in the .then()

It will definitely not wait as it is a promise. You have to use either the async/await helpers Or wait for showMsg to finish, for example showMsg().then((result)=> { //anything you want to do after dialog is closed }) in your component.

Related

extract text from image and show it in html page

i have a problem : i made a function to extract text from image with ocr space api in backend when i called it with postTypeRequest(...) in angular it worked
i added a declaration text: string and i gave it the extracted text from backend to call it in html tag and show results in my project but it shows this problem : Type 'Object' is not assignable to type 'string'
the console shows an empty data like this :
[1]: https://i.stack.imgur.com/PmRDn.png
ress is empty and its type is object
so i think ress should return string not object
home.component.ts
onSubmit() {
console.log('image', this.image);
const formData = new FormData();
formData.append('file', this.image ,'file');
return this.api.postTypeRequest('/api/scan/images', formData).subscribe((res) => {
console.log(res) ;
this.text =res //add a variable to call it in html {{text}} and show results
} )
}
scan.controller.js
const uploadImage = (req,res)=> {
let imageDetails = {
name: req.file.originalname,
};
Scan.find({ name: imageDetails.name }, (err, callback) => {
if (err) {
res.json({
err: err,
message: `There was a problem creating the image because: ${err.message}`,
});
} else {
let attempt = {
name: req.file.originalname,
imageUrl: req.file.path,
imageId: "",
};
cloudinary.uploads(attempt.imageUrl).then((result) => {
let imageDetails = {
name: req.file.originalname,
imageUrl: result.url,
imageId: result.id,
};
Scan
.create(imageDetails)
.then((image) => {
imageFilePath =imageDetails.imageUrl
const rlt = ScanService.createScan(imageFilePath).then( ()=>{
res.json({
success: true,
data: image,
ress : rlt
});
})
})
.catch((error) => {
res.json({
success: false,
message: `Error creating image in the database: ${error.message}`,
});
});
});
}
});
}
scan.service.js
const createScan = async (imageFilePath) => {
ocrSpaceApi.parseImageFromUrl(imageFilePath, options)
.then(function (parsedResult) {
console.log('parsedText: \n', parsedResult.parsedText);
console.log('ocrParsedResult: \n', parsedResult.ocrParsedResult);
return parsedResult.parsedText,parsedResult.ocrParsedResult
}).catch(function (err) {
console.log('ERROR:', err);
})}```
The error is ocorring because you have an Object on the JSON response, so you need to check before assign the String value to your text.
In this case i yould recomendo you using a type check to make sure you are receiving your data as you expect.
Something on the lines of
if(typeof res !== "string") {
this.text = "";
return;
}
this.text = res;

how to write response in switch case using nodejs

In console it shows response but in postman shows sending request like that only. How can I return a valid response in postman. How can I write code for this one i tried all.
This is my code so far:
var sendStreamingTemplate = function (req, res) {
authToken = req.headers.authorization;
userAuthObj = JSON.parse(UserAuthServices.userAuthTokenValidator(authToken));
var todayDate = new Date();
var expireDate = new Date(userAuthObj.expire_date);
tokenOK = TokenValidator.validateToken(userAuthObj.user_id, authToken).then(function (userSessions) {
if (userSessions.length === 1) {
if (expireDate >= todayDate) {
StreamingTemplateId = req.params.id;
Template.findById(StreamingTemplateId).then(function (streamingTemplate) {
if (streamingTemplate === null) {
res.status(404).json({
message: 'Streaming not found...'
})
} else {
console.log(streamingTemplate);
switch(streamingTemplate.template_name.toString().toLowerCase()){
case "notification":
//if write return response means it will return something went wrong
break;
case "invoice":
break;
case "voucher":
break;
default:
break;
}
}
}).catch(function (err) {
res.status(500).json({
message: 'something went wrong...'
});
});
} else {
res.status(401).json({
message: 'Not Authorized...'
});
}
} else {
res.status(401).json({
message: 'Token Expired...'
});
}
}).catch(function (err) {
res.status(401).json({
message: 'Token Expired...'
});
});
};
This is the the output in the console:
Instance {
dataValues: {
id: 1, template_name: 'StreamNotification', description: 'Streaming', template_content: 'Mail notification', is_active: true
},
_previousDataValues: {
id: 1, template_name: 'StreamNotification', description: 'Streaming', template_content: 'Mail notification', is_active: true
},
_changed: {
},
}
It looks like when you hit the switch statement the code isn't setting the response. Try adding this immediately after your console.log line:
res.json(streamingTemplate)
or even
res.send(streamingTemplate)
depending on the type of streamingTemplate. You might need to vary the response depending on the switch statement, in which case you could set some return value in each case then move the response to the end of the switch. Depends what you are trying to do.

sequlize transaction rollback is not working for multiple items(node js)

I have an array of object and I want an atomic transaction in sequelize.
updateCreatorDb(resultObj) {
return Promise.map(resultObj.rows, function (result: any) {
return sequelize.transaction({ autocommit: false }).then(function (t) {
return postgresService.updateByIdTrans(result.id, "user_transactions",
{ status: "sucess" }, t).then(function () {
return postgresService.updateByIdTrans(result.to_user, "user",
{ balance: sequelize.literal('balance+' + result.amount) }, t).then(function (data) {
t.commit();
}, function (error) {
t.rollback();
})
}, function (error) {
t.rollback();
});
});
});
}
updateByIdTrans(id: number, model: string, attributes, t: Transaction): Promise<void> {
let promise = new Promise<void>((resolve: Function, reject: Function) => {
logger.info("updating table " + model);
return models[model].update(attributes, { where: { id: id }, returning: true }, { transaction: t })
.then((results) => {
if (results.length > 0) {
logger.info(`Updated Object with id ${id}.`);
resolve(JSON.stringify(results[1][0]));
} else {
logger.info(`Object with id ${id} does not exist.`);
resolve(JSON.stringify(`Object with id ${id} does not exist.`));
}
}).catch((error: Error) => {
logger.error(error.message);
reject(error);
});
});
return promise;
}
If 2nd update statement fails then I want to rollback first update statement also as they are using same transaction object and not committed until 2 nd update statement is success
.with this code if I have an error in 2nd update statement then only 2nd update statement is rolled backed and first update statement get commited.

Exception with login form created by autoform (with type="normal")

I try to create simple login form with meteor and autoform but I got exception.
This is my schema for generating form:
FormSchemasLoginUsers = new SimpleSchema({
email: {
type: String,
regEx: SimpleSchema.RegEx.Email
},
password: {
type: String,
min: 6,
autoform: {
type: "password"
}
}
});
And this is my form template:
<template name="Login">
{{> quickForm id="loginUserForm" schema="FormSchemasLoginUsers" type="normal" }}
</template>
I try to handle user login with this hooks:
Template.Login.onRendered(function () {
AutoForm.addHooks('loginUserForm',
{
onSubmit: function (doc) {
console.log(doc);
Meteor.loginWithPassword(doc.email, doc.password, function(err) {
console.log(err);
if (err)
{
this.done(new Error("Login failed"));
}
this.done();
});
return false;
},
onSuccess: function(result) {
Router.go("home_private");
},
onError: function(error) {
console.log("Error: ", error);
}
}
);
});
But I got this error in firebug console:
Exception in delivering result of invoking 'login': .onSubmit/<#http://localhost:5000/app/client/views/login/login.js?b8771614cf48d3759cf0d764e51a0693caf23c81:18:5
Meteor.loginWithPassword/<.userCallback#http://localhost:5000/packages/accounts-password.js?8eae27e32c4d1bc1194f7c6dd2aaed1e33a88499:91:21
Ap.callLoginMethod/loginCallbacks<#http://localhost:5000/packages/accounts-base.js?7dabd814506e384c709f8bf707377955f9814129:612:5
_.once/<#http://localhost:5000/packages/underscore.js?46eaedbdeb6e71c82af1b16f51c7da4127d6f285:794:14
Ap.callLoginMethod/loggedInAndDataReadyCallback#http://localhost:5000/packages/accounts-base.js?7dabd814506e384c709f8bf707377955f9814129:720:5
Meteor.bindEnvironment/<#http://localhost:5000/packages/meteor.js?9730f4ff059088b3f7f14c0672d155218a1802d4:999:17
._maybeInvokeCallback#http://localhost:5000/packages/ddp-client.js?250b63e6c919c5383a0511ee4efbf42bb70a650f:3500:7
.receiveResult#http://localhost:5000/packages/ddp-client.js?250b63e6c919c5383a0511ee4efbf42bb70a650f:3520:5
._livedata_result#http://localhost:5000/packages/ddp-client.js?250b63e6c919c5383a0511ee4efbf42bb70a650f:4631:7
Connection/onMessage#http://localhost:5000/packages/ddp-client.js?250b63e6c919c5383a0511ee4efbf42bb70a650f:3365:7
._launchConnection/self.socket.onmessage/<#http://localhost:5000/packages/ddp-client.js?250b63e6c919c5383a0511ee4efbf42bb70a650f:2734:11
_.forEach#http://localhost:5000/packages/underscore.js?46eaedbdeb6e71c82af1b16f51c7da4127d6f285:149:7
._launchConnection/self.socket.onmessage#http://localhost:5000/packages/ddp-client.js?250b63e6c919c5383a0511ee4efbf42bb70a650f:2733:9
REventTarget.prototype.dispatchEvent#http://localhost:5000/packages/ddp-client.js?250b63e6c919c5383a0511ee4efbf42bb70a650f:173:9
SockJS.prototype._dispatchMessage#http://localhost:5000/packages/ddp-client.js?250b63e6c919c5383a0511ee4efbf42bb70a650f:1158:5
SockJS.prototype._didMessage#http://localhost:5000/packages/ddp-client.js?250b63e6c919c5383a0511ee4efbf42bb70a650f:1216:13
SockJS.websocket/that.ws.onmessage#http://localhost:5000/packages/ddp-client.js?250b63e6c919c5383a0511ee4efbf42bb70a650f:1363:9
meteor....a1802d4 (line 880)
I also check that login finished or not bu using Meteor.user() and user login finished successfully.
What is the problem guys??
I spend two days for it but I can't find problem.
I think you receive this issue because you are calling this.done(); inside Meteor.loginWithPassword(user, password, [callback]) which results in a wrong binding of the this value. You could either use ES6 arrow functions or just define var self = this; and then call self.done(); instead of this.done();.
For instance:
AutoForm.addHooks('loginUserForm', {
onSubmit: function(doc) {
console.log(doc);
Meteor.loginWithPassword(doc.email, doc.password, (err) => {
console.log(err);
if (err) this.done(new Error("Login failed"));
this.done();
});
return false;
},
onSuccess: function(result) {
Router.go("home_private");
},
onError: function(error) {
console.log("Error: ", error);
}
});

How to return an array from ExpressJS?

Could someone explain how this is happening? An array from Express is being destroyed before it is returned. In the example below, I am successfully populating the resData.user.apps array and can see this via the server's console log. However, when the resData object is returned the array is empty:
// Build the response
var resData = {
success: true,
user: {
email: newUserItem.email,
apps: []
}
};
// Add any default applications
Application.find({ isDefault: true, isDeleted: false }, function(err, defaultApps){
if (err){
console.log(err);
return res.status(500).send({ message: 'Failure loading default applications.' });
} else {
if (defaultApps.length < 1){
console.log('No default apps');
} else {
defaultApps.forEach(function(defaultApp){
var app = {
name: defaultApp.formalName,
url: defaultApp.url,
def: true
};
console.log(app);
resData.user.apps.push(app);
console.log('Sanity: ' + JSON.stringify(resData));
});
}
}
});
return res.send(resData);
The problem here is that the find is async so you are writing back the response before the call has completed. Move return res.send(resData); into the find callback.
Application.find({ isDefault: true, isDeleted: false }, function(err, defaultApps){
if (err){
console.log(err);
return res.status(500).send({ message: 'Failure loading default applications.' });
} else {
if (defaultApps.length < 1){
console.log('No default apps');
} else {
defaultApps.forEach(function(defaultApp){
var app = {
name: defaultApp.formalName,
url: defaultApp.url,
def: true
};
console.log(app);
resData.user.apps.push(app);
console.log('Sanity: ' + JSON.stringify(resData));
});
}
res.send(resData);
}
});

Resources