How to stop TextToSpeech in Ionic 2 - ionic2

I am having trouble stopping the playback of Ionic TextToSpeech.
Here is the function that I am calling:
...
speaking : boolean = false;
...
sayText(txt:string, loc: string){
if (this.speaking){
this.tts.stop(); // <<< does not seem to work?
this.speaking = false;
return;
}
this.speaking = true;
this.tts.speak( {text: txt, locale: loc} )
.then((val) => { this.speaking = false; },
(reject) => {console.warn(reject); this.speaking = false; })
.catch((err) => {console.error(err); this.speaking = false; });
}
This starts the speech just fine, but if it's called again during the playback it does not stop the playback...
I have injected tts: TextToSpeech in constructor, and of course imported the declaration at the beginnning:
import { TextToSpeech } from '#ionic-native/text-to-speech';
Am I missing something?
Thanks.

call tts.speak with an empty string to interrupt.
sayText(txt:string, loc: string){
if(this.speaking){
this.tts.speak({text: ''}); // <<< speak an empty string to interrupt.
this.speaking = false;
return;
}
this.speaking = true;
this.tts.speak( {text: txt, locale: loc} )
.then((val) => { this.speaking = false; },
(reject) => {console.warn(reject); this.speaking = false; })
.catch((err) => {console.error(err); this.speaking = false; });
}

Related

Jest testing - cannot clear mocks

I have this tests in my nextjs app:
jest.mock('axios');
describe('Contacts', () => {
afterEach(() => {
axios.get.mockClear();
});
it('first test', async () => {
axios.get.mockImplementation((url: string) => {
if (url.includes('?page=1')) {
return Promise.resolve(ContactsFirstPageResponse);
} else {
return Promise.resolve(ContactsSecondPageResponse);
}
});
// ...
});
it('second test', async () => {
axios.get.mockImplementation(() => Promise.resolve(ContactsEmptyResponse));
// ...
});
});
First test passed, but second received response from ContactsFirstPageResponse
In addition I added auto clearing mocks on jest config:
const nextJest = require('next/jest');
const createJestConfig = nextJest({
dir: './',
});
const { pathsToModuleNameMapper } = require('ts-jest');
const { compilerOptions } = require('./tsconfig');
const customJestConfig = {
setupFilesAfterEnv: ['<rootDir>/jest-setup.js'],
moduleDirectories: ['node_modules', '<rootDir>/'],
testEnvironment: 'jest-environment-jsdom',
moduleNameMapper: pathsToModuleNameMapper(compilerOptions.paths),
resetMocks: true,
restoreMocks: true,
};
module.exports = createJestConfig(customJestConfig);
Please for help.

nonetype' object has no attribute 'decode' error when i upload the image to database

i am new to ionic4/angular4.i need to upload the profile pic to database.i wrote code but i don't know whether it is correct or not and when i am uploading it i am getting the above mentioned error. backed i am using Django and sorry for the bad indentation.i just beginner to programming.
.ts
async sendPictureToSomewhere() {
const fileuri = await this.getPicture();
const blobinfo = await this.b64toBlob(fileuri);
await this.upload(blobinfo);
alert("done");
}
async getPicture() {
const options: CameraOptions = {
quality: 100,
destinationType: this.camera.DestinationType.FILE_URI,
encodingType: this.camera.EncodingType.JPEG,
mediaType: this.camera.MediaType.PICTURE
// targetWidth: 200
};
let fileuri = await this.camera.getPicture(options);
return fileuri;
}
b64toBlob(_imagePath) {
return new Promise((resolve, reject) => {
let fileName = "";
this.file
.resolveLocalFilesystemUrl(_imagePath)
.then(fileEntry => {
let { name, nativeURL } = fileEntry;
// get the path..
let path = nativeURL.substring(0, nativeURL.lastIndexOf("/"));
console.log("path", path);
console.log("fileName", name);
fileName = name;
// we are provided the name, so now read the file into
// a buffer
return this.file.readAsArrayBuffer(path, name);
})
.then(buffer => {
// get the buffer and make a blob to be saved
let imgBlob = new Blob([buffer], {
type: "image/jpeg"
});
console.log(imgBlob.type, imgBlob.size);
resolve({
fileName,
imgBlob
});
})
.catch(e => reject(e));
});
}
upload(_Blobinfo) {
this.profileService.postInfluencerProfile(_Blobinfo, null,
null).subscribe(
response => {
console.log(response);
},
(error: MavinError) => {
if (error instanceof NotFoundError) {
alert("Not found");
} else {
console.log(error);
}
}
);
}
}

Jasmine Karma calling Login component in angular 5

I am new to Jasmine karma test cases. I try to write the karma test case for login component. In that clicking, the submit button is not calling the onSubmit method in the component.ts file
login.component.ts
onSubmit() {
this.authService.login(this.data.username, this.data.password)
.delay(1000)
.subscribe(data => {
sessionStorage.setItem('token', JSON.stringify(data.token));
if (this.urlDirect !== null) {
window.location.href = this.sharedService.baseUrl + '/' + this.urlDirect;
} else { this.router.navigate(['/dashboard']); }
},
error => {
this.submitted = false;
setInterval(() => {
this.spinnerlogo = false;
}, 1000);
let i = 0;
const timer = setInterval(() => {
this.errorDiagnostic = 'Incorrect username or password.';
i++;
if (i === 10) {
clearInterval(timer);
this.spinnerlogo = false;
this.errorDiagnostic = null;
}
}, 500);
});
}
login.component.spec.ts
it(`entering value in username and password input controls`, () => {
userNameEl.nativeElement.value = 'admin';
passwordEl.nativeElement.value = 'admin';
fixture.detectChanges();
});
it('after entering value the button should enabled and click Action should happen', () => {
submitEl.triggerEventHandler('click', null)
// tslint:disable-next-line:no-unused-expression
expect(comp.onSubmit).toHaveBeenCalled;
// const loginButtonSpy = spyOn(comp, 'onSubmit');
// submitEl.triggerEventHandler('click', null);
// expect(loginButtonSpy).toHaveBeenCalled();
});

Aurelia Unit Testing error due to aurelia.setRoot('shell/shell');

I'm trying to implement unit test on login method but I'm getting "Cannot read property 'setRoot' of undefined" error.
Here is my Login Method:
import { inject, Aurelia, NewInstance, computedFrom } from 'aurelia-framework';
import { Router } from 'aurelia-router';
import { Server, User } from 'backend/server';
import { ValidationRules, ValidationController, validateTrigger } from 'aurelia-validation';
import { ValidationRenderer } from 'resources/validation-renderer';
#inject(Aurelia, Router, Server, NewInstance.of(ValidationController), NewInstance.of(User))
constructor(aurelia, router, server, validationController, user) {
this.router = router;
this.aurelia = aurelia;
this.validationController = validationController;
this.server = server;
this.user = user;
}
activate() {
this.validationController.validateTrigger = validateTrigger.blur;
this.validationController.addRenderer(new ValidationRenderer());
ValidationRules
.ensure(u => u.email)
.required()
.matches(/^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/)
.ensure('password')
.required()
.on(this.user);
}
logUserIn()
{
let promise = new Promise((resolve, reject) =>
{
this.loggingIn = true;
this.messageColor = 'green';
this.message = 'Authenticating...';
this.loginSuccess = false;
this.validationController.validate().then(errors => {
if (!errors.valid) {
this.loggingIn = false;
return ({error: true});
}
return this.server.authenticate(this.user.email, this.user.password);
}).then(result => {
if (!result.error) {
this.messageColor = 'green';
this.message = 'Login Successful';
this.loginSuccess = true;
this.aurelia.setRoot('shell/shell');
resolve(result);
} else {
this.message = '';
resolve();
}
}).catch(err => {
if(!this.loginSuccess)
{
this.messageColor = 'red';
this.message = err.message;
}
this.loggingIn = false;
resolve(err);
});
});
return promise;
}
My unit test code:
login.spec.js:
describe('Login Unit Test', () => {
var login = new Login();
login.validationController = new ValidationController();
login.server = new Server();
it("shouldn't allow login", (done) => {
console.log(login.messageColor);
login.logUserIn().then((result) => {
console.log(login.messageColor);
console.log(login.message);
expect(login.messageColor).toBe('red');
done();
});
});
it("Should log in", (done) => {
login.user = {email:'a#b.com', password:'abc'};
console.log(login.user.email);
console.log(login.user.password);
login.logUserIn().then((result) => {
console.log(login.messageColor);
console.log(login.message);
expect(login.messageColor).toBe('green');
done();
});
});
});
Here is the error that i'm getting
I would really appreciate any help.
Thanks.
Did you post exactly the Login code?
In this case before the constructor the #inject statement is missing.
Some like:
#inject(Aurelia, Router, Server, ValidationController, User)
constructor(aurelia, router, server, validationController, user)

Show a confirmation alert before app close ionic 2

I make one application with ionic 2. I am trying to get a confirmation alert before close the application.
How can I do it ?
export class MyApp{
constructor(public alert: AlertController,public platform: Platform){}
exit(){
let alert = this.alert.create({
title: 'Confirm',
message: 'Do you want to exit?',
buttons: [{
text: "exit?",
handler: () => { this.exitApp() }
}, {
text: "Cancel",
role: 'cancel'
}]
})
alert.present();
}
exitApp(){
this.platform.exitApp();
}
}
If you would like to enable back button exit, add event listener for it and call exit function.
You can use this.platform.registerBackButtonAction(this.exit) for it.
I could find by myself the right solution:
https://forum.ionicframework.com/t/show-a-confirmation-alert-before-app-close-ionic/63313
showedAlert: boolean;
constructor(..., public alertCtrl: AlertController) {
}
initializeApp() {
this.platform.ready().then(() => {
// Okay, so the platform is ready and our plugins are available.
// Here you can do any higher level native things you might need.
StatusBar.styleDefault();
Splashscreen.hide();
this.showedAlert = false;
// Confirm exit
this.platform.registerBackButtonAction(() => {
if (this.nav.length() == 1) {
if (!this.showedAlert) {
this.confirmExitApp();
} else {
this.showedAlert = false;
this.confirmAlert.dismiss();
}
}
this.nav.pop();
});
});
}
confirmExitApp() {
this.showedAlert = true;
this.confirmAlert = this.alertCtrl.create({
title: "Salir",
message: "¿ Esta seguro que desea salir de la aplicación ?",
buttons: [
{
text: 'Cancelar',
handler: () => {
this.showedAlert = false;
return;
}
},
{
text: 'Aceptar',
handler: () => {
this.platform.exitApp();
}
}
]
});
this.confirmAlert.present();
}
Ionic 2+ quick solution: In your app.component.ts try
ngOnInit() {
this.platform.registerBackButtonAction(() => {
if (this.nav.canGoBack()) {
this.nav.pop();
} else {
// Currently on root page
this.appClosePromt();
}
}, 1);
}
appClosePromt() {
let alert = this.alertCtrl.create({
title: '',
message: 'Do you want to exit?',
buttons: [
{
text: 'No',
role: 'cancel',
handler: () => {
// Dismiss
}
},
{
text: 'Exit',
handler: () => {
this.platform.exitApp();
}
}
]
});
alert.present();
}