Passthrough function in parameters not working - javascript

I have an array of announcements, each announcement shows up in a snackbar and has some text and a button:
// announcements.services.ts
notificationConfig: {
buttons: [
{
text: this.translateService.instant(_('Go to Insights dashboard')),
action: () => {
this.router.navigate(['/dm/statistics/insights']);
this.dismissAnnouncement(AnnouncementName.INSIGHTS_DASHBOARD);
},
},
],
},
// toast-notification.html
<div *ngFor="let button of buttons" class="buttonWrapper">
<app-button (click)="callButtonAction(button.action)">{{ button.text | translate }}</app-button>
</div>
// toast-notification.component.ts
close() {
console.log(2);
this.onClose.emit();
}
callButtonAction(action: (closeHandler: CloseHandler) => void) {
console.log(1);
action(() => this.close());
}
When I click the button in the snackbar I do the see the console.log(1) from the callButtonAction() but the this.close() is not being fired.
What I am missing here?

Looks like you are not using the handler given to action in action(() => this.close()).
Try this:
notificationConfig: {
buttons: [
{
text: this.translateService.instant(_('Go to Insights dashboard')),
action: (callback) => {
this.router.navigate(['/dm/statistics/insights']);
this.dismissAnnouncement(AnnouncementName.INSIGHTS_DASHBOARD);
callback()
},
},
],
},

Related

How to dispatch event on Push receive using Workbox?

I have a VueJS component where I listen for pushMessageEvent :
<template>
<div>
<VueBotUI
:options="options"
:is-open="isOpen"
:bot-typing="botTyping"
:input-disable="inputDisable"
:messages="messages"
#msg-send="onSend"
></VueBotUI>
</div>
</template>
<script>
export default {
components: {
VueBotUI
},
data: function () {
return {
options: {botTitle: 'test',},
user: {msg: null,},
msgRegex: /^[a-zA-Z ]+$/,
messages: []
}
},
mounted() {
document.addEventListener('pushMsgEvent', this.printPush);
},
beforeDestroy () {
document.removeEventListener('pushMsgEvent', this.printPush);
},
methods: {
printPush (e) {
console.log(e)
console.log("------------------")
console.log(e.detail)
},
}
}
</script>
And I want to fire this pushMessageEvent when I get a Push event in my service-worker:
/* eslint-disable */
importScripts(
"https://storage.googleapis.com/workbox-cdn/releases/4.3.1/workbox-sw.js"
);
// Load all ENVERYWHERE enviroment variables
importScripts('./env-vars.js')
const PushMsgEvent = new CustomEvent('pushMsgEvent', { detail: null });
workbox.core.skipWaiting();
workbox.core.clientsClaim();
self.__WB_MANIFEST;
// Listen to push event
self.addEventListener("push", (event) => {
if (event.data) {
console.log(`[Service Worker] Push had this data: "${event.data.text()}"`);
PushMsgEvent.detail = event.data.text();
//document.dispatchEvent(PushMsgEvent);
}
});
workbox.precaching.precacheAndRoute([]);
but I can't use document.dispatchEvent since I get document is not defined, is it a workaround to fire this event and catch it in my component ?
I have read about workbox-window but I can't figure out how to fire my event from the service-worker in order to catch it in the component
My solution:
service-worker.js:
// Listen to push event
self.addEventListener("push", (event) => {
if (event.data) {
self.clients.matchAll().then(clients => {
clients.forEach(client => {
client.postMessage(JSON.stringify(event.data.text()));
});
});
}
});
my component.vue :
mounted() {
navigator.serviceWorker.addEventListener('message', event => {
let msg = event.data;
this.printPush(msg);
});
},
beforeDestroy () {
navigator.serviceWorker.removeEventListener('message', event => {
this.printPush(event);
});
},
methods: {
printPush (e) {
console.log(e)
}
}

Jasmine unit testing, how do I trigger the click event of ngx-modal-dialog

I am working on an angular application and i am Unit testing the application using Jasmine.
The application uses ngx-modal-dialog(enter link description here) plugin for Pop-up Dialog Box such as a a confirmation box as a dynamic component.
What i want is to trigger the click event for the confirm or cancel, whatever the user chooses.
The code for the Pop-up Dialog box is as below:
export class SomeComponent {
constructor(private modalService: ModalDialogService) {}
cancleEditConfirmDialog() {
this.modalService.openDialog(this.viewRef, {
title: 'Discard Changes ',
childComponent: SimpleModalComponent,
data: {
text: 'Changes will not be saved. Do you want to proceed?'
},
settings: {
closeButtonClass: 'close theme-icon-close'
},
actionButtons: [
{
text: 'Discard',
buttonClass: 'btn btn-success',
onAction: () => new Promise((resolve: any) => {
// invoke delete
// do something such as discard changes
resolve()
})
},
{
text: 'Cancel',
buttonClass: 'btn btn-danger',
onAction: () => new Promise((resolve: any) => {
// cancel and close popup
setTimeout(() => {
resolve();
}, 20);
})
}
]
});
}
}
how do i trigger the onAction: => () in the click event for discard button
and for cancel button.
There is a problem, with testing this modal dialog, if the viewRef passed into the modalService is the actual component under test itself. This is because the modal dialog gets added into the dom outside the viewRef. So you could only access the elements inside the test using document.getElementById which would be possible, but you wouldn't have the chance to use all those nice debugElement features and so on.
There is a way though: if it's not a problem to use a div inside the component as the viewRef than the test could be done.
stackblitz
This means your template would need to look like this:
template
<div #parentDialog>
<button type="button" (click)="cancleEditConfirmDialog()">Open Dialog</button>
</div>
If thats the case the component would look like this:
component.ts
#ViewChild('parentDialog', {read: ViewContainerRef}) parentVCR;
constructor(private modalService: ModalDialogService) {}
cancleEditConfirmDialog() {
this.modalService.openDialog(this.parentVCR, {
title: 'Discard Changes ',
childComponent: SimpleModalComponent,
data: {
text: 'Changes will not be saved. Do you want to proceed?'
},
settings: {
closeButtonClass: 'close theme-icon-close'
},
actionButtons: [
{
text: 'Discard',
buttonClass: 'btn btn-success',
onAction: () => new Promise((resolve: any) => {
// invoke delete
// do something such as discard changes
resolve()
})
},
{
text: 'Cancel',
buttonClass: 'btn btn-danger',
onAction: () => new Promise((resolve: any) => {
// cancel and close popup
setTimeout(() => {
resolve();
}, 20);
})
}
]});
}
And finally your test case:
test
describe('AppComponent', () => {
let fixture: ComponentFixture<AppComponent>;
let component: AppComponent;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [ModalDialogModule.forRoot()],
declarations: [ AppComponent],
schemas: [NO_ERRORS_SCHEMA]
});
fixture = TestBed.createComponent(AppComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('open dialog and cancel', fakeAsync(() => {
let buttonDebugElems: DebugElement[] = fixture.debugElement.queryAll(By.css('button'));
expect(buttonDebugElems.length).toEqual(1);
expect(buttonDebugElems[0].nativeElement.innerText).toEqual('Open Dialog');
// Open
buttonDebugElems[0].triggerEventHandler('click', null);
fixture.detectChanges();
buttonDebugElems = fixture.debugElement.queryAll(By.css('button'));
expect(buttonDebugElems.length).toEqual(3);
expect(buttonDebugElems[1].nativeElement.innerText).toEqual('Discard');
expect(buttonDebugElems[2].nativeElement.innerText).toEqual('Cancel');
// cancel
buttonDebugElems[2].triggerEventHandler('click', null);
// needed to wait for the promise to resolve (20 needed due to the timeout of the cancel promise)
tick(20);
buttonDebugElems = fixture.debugElement.queryAll(By.css('button'));
expect(buttonDebugElems.length).toEqual(1);
// todo expect the things the action changed inside you component.
}));
it('open dialog and discard', fakeAsync(() => {
let buttonDebugElems: DebugElement[] = fixture.debugElement.queryAll(By.css('button'));
expect(buttonDebugElems.length).toEqual(1);
expect(buttonDebugElems[0].nativeElement.innerText).toEqual('Open Dialog');
// open
buttonDebugElems[0].triggerEventHandler('click', null);
fixture.detectChanges();
buttonDebugElems = fixture.debugElement.queryAll(By.css('button'));
expect(buttonDebugElems.length).toEqual(3);
expect(buttonDebugElems[1].nativeElement.innerText).toEqual('Discard');
expect(buttonDebugElems[2].nativeElement.innerText).toEqual('Cancel');
// discard
buttonDebugElems[1].triggerEventHandler('click', null);
// needed to wait for the promise to resolve
tick();
buttonDebugElems = fixture.debugElement.queryAll(By.css('button'));
expect(buttonDebugElems.length).toEqual(1);
// todo expect the things the action changed inside you component.
}));
});

Remove data from Firebase with Ionic 3

I want to remove a data from firebase but all documents I have found all said use .remove() function as I show as codesnippet here. But this is not work at Ionic 3. Is that function is changed or what is the point that I didn't see.
selectBook(indexOfBook : Book){
this.actionSheetCtrl.create({
title: indexOfBook.nameOfBook,
buttons:[{
text:'Edit',
handler: () =>{
// TODO:Send the user to EditPage
}
},
{
text:'Delete',
role: 'destructive',
handler: () => {
this.getBookRef$.remove(indexOfBook.key);//**************************************
}
},
{
text:'Cancel',
role:'cancel',
handler: () =>{
console.log("The user has selected the cancel button");
}
}
]
}).present();
}

how to dismiss an alert in React Native?

I am using an Alert , and when i am navigating to previous screen on clicking of ok button this alert is not dismissing.
its showing up again in that back screen.
How i can stop this alert showing up again.
I am trying this code.
showErrorAlert = () => {
Alert.alert(
CONSTANTS.SOME_ERROR_OCCURED,
'',
[{ text: 'OK', onPress: () => this.loggingOut() },],)
};
loggingOut = () => {
console.log("coming here");
};
Can you please try the following code, you can try adding { cancelable: false }.
For more information go here
showErrorAlert = () => {
Alert.alert(
CONSTANTS.SOME_ERROR_OCCURED,
'',
[{ text: 'OK', onPress: () => this.loggingOut() },],
{ cancelable: false })
};
loggingOut = () => {
console.log("coming here");
};

Stop alertCtrl auto triggering cancel in Ionic 2

I've got an alert controller that, when triggered, opens and then immediately closes without me doing anything.
let alert = this.alertCtrl.create({
title: 'Requires Login',
message: 'Please register or log in to add to cart.',
buttons: [
{
text: 'Cancel',
handler: () => {
console.log('Cancel clicked');
}
},
{
text: 'Login',
handler: () => {
this.logOut();
}
}
]
});
alert.present();
I can't find anything wrong and I'm wondering what is causing this issue? When I run the application through my phone I get the error, but when I run it through the browser, no error.
Here's a working example from my current project
logout() {
let confirm = this.alertCtrl.create({
title: 'Confirm',
message: 'Are you sure you want to logout?',
buttons: [
{
text: 'No',
handler: () => { }
},
{
text: 'Yes',
handler: () => {
this.removeNotificationRegistrationAndLogOut(LoginPage, true);
}
}
]
});
confirm.present();
}

Categories

Resources