nested Mat-dialogBox closing issue - html

I have one parent raster component from where I am opening my first dialog box and from that dialog box component, i am opening second dialog box. I want to pass data from last dialog box to my parent raster and meanwhile need to close all the dialog boxes but I am not able to get data from second dialog box to first dialog box and because of this, i dont get data in raster component.
Can someone help me to solve this? I have tried to do all the things but still getting undefined. Any kind of help would be nice.
Kindly find my below code.
raster.component.ts
openDialogbox(value): void {
this.emptyTile = value;
const dialogRef = this.dialog.open(AddNewFlyerComponent, {
width: '100em',
height: '50em',
data: {
flyerArray: this.flyers,
emptyPosition: this.emptyTile,
page: this.flyers[0].Seite,
year: this.flyers[0].Jahr,
week: this.flyers[0].KW,
}
});
dialogRef.afterClosed().subscribe(result => {
console.log('The raster dialog was closed', result);
});
}
AddNewFlyerComponent.ts
openDialog(werbenumber): void {
const dialogRef = this.dialog.open(CreateNewFlyerComponent, {
width: '100em',
height: '50em',
data: {
flyerArray: this.data.flyerArray,
werbenumber: werbenumber,
emptyTile: this.data.emptyPosition,
page: this.data.page,
week: this.data.week,
year: this.data.year
}
});
dialogRef.afterClosed().subscribe(result => {
console.log('The 1st dialog was closed', result); // getting undefined
});
}
CreateNewFlyerComponent.ts
addFlyerToEmptyPosition(werbedata: WerbeData) {
const newFlyer = {
ArtNr: this.werbedata.ArtNr,
Filiale: this.werbedata.FILIALE,
Jahr: this.data.flyerArray[0].Jahr,
KW: this.data.flyerArray[0].KW,
Pos: this.data.emptyTile,
Raster: this.data.flyerArray[0].Raster,
Seite: this.data.flyerArray[0].Seite,
WERBE_NR: this.werbedata.WERBE_NR,
EUR_VK: this.a,
EUR_VK_Einheit: this.b,
VK_Einheit: this.c
};
this.flyerHammService.createNewFlyer(newFlyer)
.then(
(response: any) => {
this.returnFlyer = response.data[0]; // This returnFlyer, I want to pass
this.matSnackBar.open('Neuer Flyer wurde erstellt', 'Undo', {
duration: 3000
});
}
).catch(
error => console.log(error)
);
}
CreateNewFlyerComponent.ts
<button mat-dialog-close mat-raised-button [color]="'success'" [mat-dialog-close]="returnFlyer" (click)="addFlyerToEmptyPosition(werbedata)">
{{ 'SPEICHERN' }}
<mat-icon>save</mat-icon>
</button>

Use the same data object for both dialogs. Instead of creating a new object, update the original data object with additional data and pass it into the second dialog:
AddNewFlyerComponent.ts
openDialog(werbenumber): void {
this.data.emptyTile = this.data.emptyPosition; // or was that a typo?
this.data.werbenumber = werbenumber; // or use Object.defineProperty()
const dialogRef = this.dialog.open(CreateNewFlyerComponent, {
width: '100em',
height: '50em',
this.data
});
dialogRef.afterClosed().subscribe(result => {
console.log('The 1st dialog was closed', result); // getting undefined
});
}
To pass the data back to raster, use the same approach:
raster.component.ts
data;
openDialogbox(value): void {
this.emptyTile = value;
this.data = {
flyerArray: this.flyers,
emptyPosition: this.emptyTile,
page: this.flyers[0].Seite,
year: this.flyers[0].Jahr,
week: this.flyers[0].KW,
}
const dialogRef = this.dialog.open(AddNewFlyerComponent, {
width: '100em',
height: '50em',
data: this.data
});
dialogRef.afterClosed().subscribe(result => {
console.log('The raster dialog was closed', result);
});
}

Related

Json string array to object in Vuex

In my states I have categories. In the categories array every each category have a settings column where I have saved json array string.
My question it is,how can I turn my string to object by filtering the response ?
My response:
[{"id":4,"name":"Vehicles","slug":"vehicles","settings":"[{"edit":true,"searchable":true}]","created_at":"2019-01-26 16:37:36","updated_at":"2019-01-26 16:37:36"},
This is my loading action for the categories:
const loadCategories = async ({ commit }, payload) => {
commit('SET_LOADING', true);
try {
const response = await axios.get(`admin/store/categories?page=${payload.page}`);
const checkErrors = checkResponse(response);
if (checkErrors) {
commit('SET_DIALOG_MESSAGE', checkErrors.message, { root: true });
} else {
commit('SET_STORE_CATEGORIES', response.data);
}
} catch (e) {
commit('SET_DIALOG_MESSAGE', 'errors.generic_error', { root: true });
} finally {
commit('SET_LOADING', false);
}
};
This is my SET_STORE_CATEGORIES:
const SET_STORE_CATEGORIES = (state, payload) => {
state.categories=payload.data;
state.pagination = {
currentPage: payload.current_page,
perPage: payload.per_page,
totalCategories: payload.total,
totalPages: payload.last_page,
};
};
Here I would like to add to modify the value ,to turn the string to object.
Had to add:
let parsed=[];
parsed=response.data.data.map((item)=>{
console.log(item);
let tmp=item;
tmp.settings=JSON.parse(item.settings);
return tmp;
});
response.data.data=parsed;
commit('SET_STORE_CATEGORIES', response.data);
You could map your response data as follows by parsing that string to an object :
let parsed=[];
parsed=response.data.map((item)=>{
let tmp=item;
tmp.settings=JSON.parse(item.settings);
return tmp;
});
commit('SET_STORE_CATEGORIES', parsed);

Object from Observable then Array from Observable inside a foreach. how to order it?Asynchronous Angular 4/5

Here is my problem.
I'm running a method that sends me a json (method = myTableService.getAllTables ()), to create an object (object = this.myTables).
Then I execute the method for each, for each element of this.myTables I execute a new request (request = this.myTableService.getTableStatut (element.theId)).
I retrieve data from a new json to create an object (object = myTableModel).
Each result will be added to this.myTableListProvisory.
The problem is the order of execution.
It execute the console.log before the end of the for each...
This.myTableListProvisory.length and this.myTableList.length return 0.
How to wait for the end of the for each run before running the console.log?
Thank you
ngOnInit() {
this.myTableService.getAllTables()
.subscribe(data => {
this.myTables = data;
this.myTableList = this.getAllTableStatut(this.myTables);
console.log("this.myTableList.length : " + this.myTableList.length);
}, err => {
console.log(err);
})
}
getAllTableStatut(myTables: any) {
this.myTableListProvisoire = [];
myTables.forEach(element => {
this.myTableService.getTableStatut(element.theId)
.subscribe(data => {
this.statut = data;
this.myTableModel = new MyTableModel(element.tableNumber, this.statut.name, element.theId);
this.myTableListProvisoire.push(this.myTableModel);
})
console.log("this.myTableListProvisoire.length : " + this.myTableListProvisoire.length);
})
return this.myTableListProvisoire;
}
Result of console.log
this.myTableListProvisoire.length : 0
this.myTableList.length : 0
UPDATE
I have simplified the code ... I put it in its entirety for the understanding. What I need is to sort the array after it is done. The problem is that I don't know how to use a flatMap method in a query inside a foreach ... I have temporarily placed the sort method inside the subscribe which is a bad solution for the performance. That's why I want to do my sort after the creation of the array. Thank you
export class MyTableComponent implements OnInit {
myTables: any;
statut: any;
myTableModel: MyTableModel;
myTableList: Array<MyTableModel>;
myTableListProvisoire: Array<MyTableModel>;
i: number;
j: number;
myTableModelProvisoire: MyTableModel = null;
constructor(public myTableService: MyTableService) { }
ngOnInit() {
this.myTableService.getAllTables()
.subscribe(data => {
this.myTables = data;
this.myTableList = this.getAllTableStatut(this.myTables);
}, err => {
console.log(err);
})
}
getAllTableStatut(myTables: any) {
this.myTableListProvisoire = [];
myTables.forEach(element => {
this.myTableService.getTableStatut(element.theId)
.subscribe(data => {
this.statut = data;
this.myTableModel = new MyTableModel(element.tableNumber, this.statut.name, element.theId);
this.myTableListProvisoire.push(this.myTableModel);
for (this.j = 0; this.j < this.myTableListProvisoire.length; this.j++) {
for (this.i = 0; this.i < this.myTableListProvisoire.length - 1; this.i++) {
if (this.myTableListProvisoire[this.i].getTableNumber() > this.myTableListProvisoire[(this.i + 1)].getTableNumber()) {
this.myTableModelProvisoire = this.myTableListProvisoire[this.i];
this.myTableListProvisoire[this.i] = this.myTableListProvisoire[(this.i + 1)];
this.myTableListProvisoire[(this.i + 1)] = this.myTableModelProvisoire;
}
}
}
}, err => {
console.log(err);
})
}, err => {
console.log(err);
})
return this.myTableListProvisoire;
}
}
Well Observables are asynchronous actions and will be executed after finishing the current execution block. So when the js engine comes to your
this.myTableService.getTableStatut(element.theId)
.subscribe(data => {
this.statut = data;
this.myTableModel = new MyTableModel(element.tableNumber, this.statut.name, element.theId);
this.myTableListProvisoire.push(this.myTableModel);
})
it will only create a subscription, but the code inside of it will be executed after all the other code in the block. So that's why your console.log is being executed before you get any data. So you need to place it inside the .subscribe block to see the. I think there can be a better solution to get the data, but I don't know the structure of the app, so I can't advice. If you create an example on https://stackblitz.com/ I could probably help you out with a better solution.

Nativescript : camera photo asset with nativescript-ocr

I'm trying to take a picture with the nativescript camera module and to run
the nativescript-ocr module (https://github.com/EddyVerbruggen/nativescript-ocr) on it .
Here is my code :
public saveToGallery: boolean = true;
public keepAspectRatio: boolean = true;
public width: number = 300;
public height: number = 300;
private ocr: OCR;
constructor() {
this.ocr = new OCR();
}
ngOnInit(): void {
}
onTakePhoto() {
let options = {
width: this.width,
height: this.height,
keepAspectRatio: this.keepAspectRatio,
saveToGallery: this.saveToGallery
};
takePicture(options).
then((imageAsset) => {
console.log("Result is an image asset instance");
let img: ImageSource = new ImageSource();
img.fromAsset(imageAsset).then((success) => {
if (success) {
this.ocr.retrieveText({
image: img,
whitelist: "ABCDEF",
blacklist: "0123456789",
onProgress: (percentage: number) => {
console.log(`Decoding progress: ${percentage}%`);
}
}).then(
(result: RetrieveTextResult) => {
console.log(`Result: ${result.text}`);
}, (error: string) => {
console.log(`Error: ${error}`);
})
}
});
}).catch((err) => {
console.log("Error -> " + err.message);
});
}
onRequestPermissions() {
requestPermissions();
}
}
Camera plugin works fine, takes and saves a picture, but when i'm running onTakePhoto i get this error message :
"Error in ocr.retrieveText: Error: java.lang.IllegalArgumentException: Data path does not exist!"
i'm not sure to use the .fromAsset the right way,
but i try a lot of thing to solve this problem
what i'm doing wrong?
Resolve : i didn't create corectly my tesseract/tessdata folder

Stripe and back4app : Cannot read property 'id' of undefined

I'm trying to integrate payment in my app.
Here is the cloud code for Back4app :
var Stripe = require("stripe")(
"TestSecretKeyOk"
);
Parse.Cloud.define("purchaseItem", function(request, response) {
var item, order;
Parse.Promise.as().then(function() {
var itemQuery = new Parse.Query('Item');
itemQuery.equalTo('ItemName', request.params.itemName);
return itemQuery.first(null,{useMasterKey: true}).then(null, function(error) {
return Parse.Promise.error('Sorry, this item is no longer available.');
});
},{useMasterKey: true}).then(function(result) {
if (!result) {
return Parse.Promise.error('Sorry, this item is no longer available.');
} else if (result.get('quantityAvailable') <= 0) {
return Parse.Promise.error('Sorry, this item is out of stock.');
}
item = result;
item.increment('quantityAvailable', -1);
return item.save(null,{useMasterKey: true}).then(null, function(error) {
console.log('Decrementing quantity failed. Error: ' + error);
return Parse.Promise.error('An error has occurred. Your credit card was not charged.');
});
},{useMasterKey: true}).then(function(result) {
if (item.get('quantityAvailable') < 0) { // can be 0 if we took the last
return Parse.Promise.error('Sorry, this item is out of stock.');}
order = new Parse.Object("Order");
order.set('name', "azeaze"); //You can pass the client data from request.params at the begining
order.set('email', "a#gmail.com");
order.set('address', "NA");
order.set('zip', "99999");
order.set('city_state', "CA");
order.set('item', item.get('ItemName'));
order.set('fulfilled', false);
order.set('charged', false);
return order.save(null,{useMasterKey:true}).then(null, function(error) {
return Parse.Promise.error('An error has occurred. Your credit card was not charged.');
});
},{useMasterKey:true}).then(function(order) {
return Stripe.charges.create({
amount: item.get('price')*100, // It needs to convert to cents
currency: "usd",
source: request.params.cardToken,
description: "Charge for dominwong4#gmail.com"
}, function(err, charge) {
// asynchronously called
console.log(charge.id);
});
},{useMasterKey:true}).then(function(purchase) {
order.set('stripePaymentId', purchase.id);
order.set('charged', true);
order.save(null,{useMasterKey:true});
},{useMasterKey:true}).then(function() {
//your email logic
},{useMasterKey:true}).then(function() {
response.success('Success');
}, function(error) {
response.error('erreur trouvé ' + error);
});
});
Everything seems working fine :
-Stripe telling me payment is ok in their backend and no error .
But even if Parse Dashboard implement the order
StripePaymentID still null and this error raising :
TypeError: Cannot read property 'id' of undefined
So i don't understand what's not working , if you can help , i would be gratefull.
I recommend you update your Stripe Version. Just need to upload a file, with the name: "package.json" and insert the content like the structure below:
{
"dependencies": {
"stripe": "^5.8.0"
}

Angular 2 periodically pull real time data

I have developed an app which basically has admin and client portal running in separate ports and when an order is placed from client side, the admin dashboard should be able to get the new order shown.
Basically the view has to be refreshed to keep an updated UI.
For which i have referred the below link:
http://beyondscheme.com/2016/angular2-discussion-portal
Below is what i have tried.
order-issue.component.ts
ngOnInit() {
const user_id = {
user_ids: this.user_id
};
// To display the Pending Orders into the table
this.orderService.getAllOrders("Pending").subscribe(data => {
if (data.success && data.Allorders.length != 0) {
for (let i = 0; i < data.Allorders.length; i++) {
this.orderService
.getOrderItemsByNo(data.Allorders[i].orderNo)
.subscribe(subData => {
data.Allorders[i].orderItems = subData;
});
}
this.source = data.Allorders; //To display the data into smart table
this.refreshData(); //For real time refresh
} else {
this.flashMessage.show("No Pending Orders", {
cssClass: "alert-success",
timeout: 300000
});
}
});
private refreshData(): void {
this.commentsSubscription = this.orderService.getAllOrders("Pending").subscribe(data => {
this.data = data;
console.log(data); //able to see the new orders
this.subscribeToData();
});
private subscribeToData(): void {
this.timerSubscription = Observable.timer(5000).first().subscribe(() => this.refreshData());
}
My service(orderService) will get all the orders:
getAllOrders(status) {
let headers = new Headers();
headers.append('Content-Type', 'application/json');
return this.http.post(`${BASE_URL}/orders/getAllOrdersWithItems`, { status: status }, { headers: headers })
.map(res => res.json());
}
Ok i am able to fix it with below change.
//Function which refreshes the data in real time without page refresh
private refreshData(): void {
this.commentsSubscription = this.orderService.getAllOrders("Pending").subscribe(data => {
this.source = data.Allorders; //Updated here! and it worked
console.log(this.source);
this.subscribeToData(); //On success we call subscribeToData()
});
}