ionic 2 Alert not working on webpage - ionic-framework

I would like to raise an alert on Ionic2 when the device does not have a Camera.
When i launch : ionic serve
then i try to display the message as follow :
let alert = Alert.create({
title: 'Camera not found',
subTitle: 'It seems your camera is not working on your device',
buttons: ['Ok']
});
this.nav.present(alert);
i have a javascript error
Uncaught EXCEPTION: Error during evaluation of "click"
ORIGINAL EXCEPTION: TypeError: rootNav.getActive is not a function
ORIGINAL STACKTRACE:
TypeError: rootNav.getActive is not a function
at Tab.NavController.present (http://localhost:8100/build/js/app.bundle.js:46996:36)
at SmartScan.takePicture (http://localhost:8100/build/js/app.bundle.js:60864:23)
at AbstractChangeDetector.ChangeDetector_SmartScan_0.handleEventInternal (eval at <anonymous> (http://localhost:8100/build/js/app.bundle.js:14578:17), <anonymous>:185:36)
at AbstractChangeDetector.handleEvent (http://localhost:8100/build/js/app.bundle.js:13892:25)
at AppView.dispatchEvent (http://localhost:8100/build/js/app.bundle.js:18772:46)
at AppView.dispatchRenderEvent (http://localhost:8100/build/js/app.bundle.js:18766:22)
at DefaultRenderView.dispatchRenderEvent (http://localhost:8100/build/js/app.bundle.js:33592:39)
at eventDispatcher (http://localhost:8100/build/js/app.bundle.js:33258:22)
at http://localhost:8100/build/js/app.bundle.js:33329:40

In alert.js:
import {Page, Alert, NavController} from 'ionic-angular';
#Page({
templateUrl: 'build/pages/alert/alert.html'
})
export class AlertPage {
static get parameters() {
return [[NavController]];
}
constructor(nav) {
this.nav = nav;
}
showAlert() {
let alert = Alert.create({
title: 'New Friend!',
subTitle: 'Your friend, Obi wan Kenobi, just accepted your friend request!',
buttons: ['Ok']
});
this.nav.present(alert);
}
}
In alert.html:
<button block dark (click)="showAlert()">test</button>

Try this:
with this structure of folder and files
In:
home.html
<ion-header>
<ion-navbar>
<ion-title>Ionic 2 Notifications</ion-title>
</ion-navbar>
</ion-header>
<ion-content padding>
<button block dark (click)="showAlert()">Alert</button>
</ion-content>
In:
home.ts
import {Component} from "#angular/core";
import {NavController, AlertController} from 'ionic-angular';
#Component({
templateUrl: 'home.html'
})
export class HomePage {
constructor(public alertCtrl: AlertController) {
}
showAlert() {
let alert = this.alertCtrl.create({
title: 'New Friend!',
subTitle: 'Your friend, Obi wan Kenobi, just accepted your friend request!',
buttons: ['OK']
});
alert.present();
}
}
I got this information from the documentation site:
https://ionicframework.com/docs/v2/components/#action-sheets

I am also working on ionic2 and was in the need to implement "PopUp" window in my existing application.
I try many for that by does not get my task accomplished, finally i did something like this-
pop-up.html
<button block dark (click)="showAlert()">Help Window</button>
pop-up.ts
import { Component } from '#angular/core';
import { Alert, NavController, NavParams} from 'ionic-angular';
#Component({
templateUrl: 'build/pages/pop-up/pop-up.html',
})
export class PopUpPage {
static get parameters() {
return [[NavController]];
}
constructor(private nav: NavController) {
this.nav = nav;
}
showAlert() {
let alert = Alert.create({
title: 'Help Window!',
subTitle: 'Mindfulness is here for you and your soul. We are intended to stablish your connection to All Mighty.',
buttons: ['Cancle']
});
this.nav.present(alert);
}
}
And that work fine for me.
Hope it will work for you too.

It seems that is not yet ready ...
investigating the code
this.nav.present(alert);
it is passing here and returns :
if (rootNav['_tabs']) {
// TODO: must have until this goes in
// https://github.com/angular/angular/issues/5481
void 0;
return;
}

Related

setting global variable in ipcRenderer.on eventhandler running ionic on electron does not work

This is my code in home.ts to receive values from main-process
import { Component } from '#angular/core';
import { NavController } from 'ionic-angular';
declare var electron : any;
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
arguments: any="ping";
constructor(public navCtrl: NavController) {
}
ionViewDidLoad() {
electron.ipcRenderer.send("test_channel","ping");
electron.ipcRenderer.on("test_channel", function (err,arg) {
this.arguments=arg; // receive new value "pong" from main.js
console.log("Message received from electron: "+arg); // works fine
});
console.log("Message received from electron: "+this.arguments); //does not work, still default value
};
}
This is added in my code in main.js, and it works to receive the event from render-process
var ipcMain = require('electron').ipcMain;
mainWindow.webContents.openDevTools();
ipcMain.on("test_channel",function(err,arg){
console.log(err);
console.log("Received message: "+arg);
global.sharedObj = {prop1: arg};
console.log("Sending message back!");
// Send message back!
mainWindow.webContents.send("test_channel",arg+'yeah');
})
This is added in my index.html, to make it run for ionic
<script>
const electron = require('electron');
</script>
First of all don't duplicate the message name. and in the main.js , send the event request to the renderer process using event.sender.send as shown below:-
ipcMain.on('message_name', (event,args) => {
event.sender.send('message_name_2', args)
});

PopoverController Ionic 4?

How does the PopoverController work in Ionic 4?
The current documentation is incorrect and there's no breaking changes for it?
const popover = this.popoverCtrl.create({
component: 'PopupMenuComponent',
ev: event
});
popover.present();
I've created a Component and when I try to present it, I receive the below error...
[ts] Property 'present' does not exist on type 'Promise<HTMLIonPopoverElement>'. Did you forget to use 'await'?
Thanks.
In your example, you didnt await it. As of Alpha-7 the create method returns a promise. You can find the latest documentation here. Take alook at this example:
import { Component } from '#angular/core';
import { PopoverController } from '#ionic/angular';
#Component({
template: `
<ion-list no-margin>
<ion-item (click)="onDismiss()">Dismiss</ion-item>
</ion-list>
`
})
export class PopupMenuComponentPopover {
constructor(private popoverCtrl: PopoverController) {
}
async onDismiss() {
try {
await this.popoverCtrl.dismiss();
} catch (e) {
//click more than one time popover throws error, so ignore...
}
}
}
And here is how to open it:
async openPopover(args) {
const popover = await this.popoverController.create({
component: PopupMenuComponentPopover,
ev: args,
translucent: false
});
return await popover.present();
}
Edit: here is you can call it:
#NgModule({
...
declarations: [DashboardWebsiteMorePopover],
entryComponents: [DashboardWebsiteMorePopover],
...
})
export class PopupMenuComponentModule {}

Menu items not appearing programmatically ionic 3 when user signs in. (AWS Cognito)

I am building an ionic app using AWS as a backend (has been challenging!), and for some reason on my user sign-in page, I got this nasty bug that wasn't there when I was using firebase as the backend. In a nutshell, my side menu has items that should appear based on whether the user is logged in or not. If the user is logged in, the menu should have a logout item. If the user is not logged in, the menu should either not have any options, or a redundant sign-in option.
I got the hard part down, which was setting up AWS Cognito to work the sign-in logic, and setting the correct root page, however, after a user logs in, the menu does not show the logout option.
Funny thing, if I reload the app, the menu does show the logout option. Not sure why. Also weird, after I reload the app and I click the logout button, the correct options for a user that is not logged in do appear in the menu. If someone can take a look and tell me why the menu options only render correctly when I log out and if I log in only after I reload the app, I would be very grateful! Thank you in advance for your time! Code below...
app.component.ts:
import { Component } from '#angular/core';
import { Platform, NavController, MenuController } from 'ionic-angular';
import { StatusBar } from '#ionic-native/status-bar';
import { SplashScreen } from '#ionic-native/splash-screen';
import { TabsPage } from '../pages/tabs/tabs';
import { SignInPage } from '../pages/sign-in/sign-in';
import { AuthService } from '../services/auth';
#Component({
templateUrl: 'app.html'
})
export class MyApp {
rootPage: any;
isLoggedIn //this variable holds the status of the user and determines the menu items;
constructor(platform: Platform,
statusBar: StatusBar,
splashScreen: SplashScreen,
private menuCtrl: MenuController,
private authService: AuthService) {
this.verifyUserstate(); //method to check if a user is logged in
console.log(this.isLoggedIn); //debug line
console.log(this.menuCtrl.get()); //debug line
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();
});
}
onLoad(page: any) {
console.log("onLoad");
this.nav.setRoot(page);
this.menuCtrl.close();
}
onLogout() {
this.authService.logout();
this.verifyUserstate();
this.menuCtrl.close();
}
verifyUserstate() {
console.log("in verify userstate");
this.authService.isAuthenticated()
.then(() => {
this.isLoggedIn = true; //if a user is logged in = true
this.rootPage = TabsPage;
console.log(this.isLoggedIn); // more debug
})
.catch((error) => {
this.isLoggedIn = false; //if user is not logged in = false
this.rootPage = SignInPage;
console.log(this.isLoggedIn); //more debug
});
}
}
app.html:
<ion-menu [content]="nav">
<ion-header>
<ion-toolbar>
<ion-title>Menu</ion-title>
</ion-toolbar>
</ion-header>
<ion-content>
<ion-list>
<button ion-item icon-left (click)="onLoad(signinPage)" *ngIf="!isLoggedIn"> <!-- check isLoggin-->
<ion-icon name="log-in"></ion-icon>
Sign In
</button>
<button ion-item icon-left (click)="onLogout()" *ngIf="isLoggedIn">
<ion-icon name="log-out"></ion-icon>
Log Out
</button>
</ion-list>
</ion-content>
auth.ts:
import { Injectable } from "#angular/core";
import { AlertController } from "ionic-angular";
import { CognitoUserPool, AuthenticationDetails, CognitoUser, CognitoUserSession } from "amazon-cognito-identity-js";
const POOL_DATA = {
UserPoolId: "xx-xxxx-X_XXXX",
ClientId: "You do not need to know :)"
}
const userPool = new CognitoUserPool(POOL_DATA);
export class AuthService {
signin(email: string, password: string) {
let message: string;
var authenticationData = {
Username : email,
Password : password,
};
var authDetails = new AuthenticationDetails(authenticationData);
let userData = {
Username: email,
Pool: userPool
}
let cognitoUser = new CognitoUser(userData);
return new Promise((resolve, reject) => {
cognitoUser.authenticateUser(authDetails, {
onSuccess(result: CognitoUserSession) {
console.log(result)
resolve("Success!")
},
onFailure(error) {
let message: string = error.message;
reject(message);
}
}
logout() {
this.getAuthenticatedUser().signOut();
}
isAuthenticated() {
return new Promise((resolve, reject) => {
let user = this.getAuthenticatedUser();
if (user) {
user.getSession((err, session) => {
if(session.isValid()) {
resolve(true);
} else if (err) {
reject(err.message);
}
})
} else {
reject("Not authenticated");
}
});
}
}
Finally, the sign-in.ts file (where the magic of login in happens):
import { Component } from '#angular/core';
import { NgForm } from '#angular/forms';
import { LoadingController, AlertController } from 'ionic-angular';
import { AuthService } from '../../services/auth';
import { NavController } from 'ionic-angular/navigation/nav-controller';
import { MyApp } from '../../app/app.component';
#Component({
selector: 'page-sign-in',
templateUrl: 'sign-in.html',
})
export class SignInPage {
constructor(private authService: AuthService,
private loadingCtrl: LoadingController,
private alertCtrl: AlertController,
private navCtrl: NavController) {
}
onSignin(form: NgForm) {
const loading = this.loadingCtrl.create({
content: "Signing you in..."
});
loading.present();
this.authService.signin(form.value.email, form.value.password)
.then(data => {
this.navCtrl.setRoot(MyApp); /*navigate to myApp again to reverify the
*login status. This sets the right rootPage,
*but I have a feeling here also lies the menu problem.
*/
console.log(data);
})
.catch(error => {
console.log(error);
let alert = this.alertCtrl.create({
title: "Oops",
message: error,
buttons: ["Ok"]
});
alert.present();
})
loading.dismiss();
}
}

image selection des not work in ionic 2 app

i am trying to open the photolibrary of android to select images using ionic 2.
here is the code of the home.ts in witch the camera plugin is used.
import { Component } from '#angular/core';
import { NavController } from 'ionic-angular';
import {Camera} from '#ionic-native/camera';
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
image640:any;
constructor(public navCtrl: NavController,public camera : Camera)
{
}
openGallery()
{
var options = {
quality: 100,
sourceType: this.camera.PictureSourceType.PHOTOLIBRARY,
saveToPhotoAlbum: true,
correctOrientation: true,
};
this.camera.getPicture(
options
).then(
(imageData)=>
{
this.image640 = 'data:image/jpeg;base64,'+imageData;
},
(err) =>
{
console.log(err);
}
);
}
}
And the code of the home.html is below :
<ion-header>
<ion-navbar>
<ion-title align="center">
Blank
</ion-title>
</ion-navbar>
</ion-header>
<ion-content padding>
<img src="image640" *ngIf="image640"/>
<Button align="center" ion-button (click)="openGallery()">Open
Gallery</Button>
</ion-content>
but when i click on the opengallery button, the android library is opened but when i select an image, a blank screen appear during about 8 seconds, and after that, the it is the rootpage that is displayed. Then i cannot see the selected image in my page.
can somebody help ?
Set options
var options = {
quality: 100,
sourceType: this.camera.PictureSourceType.PHOTOLIBRARY,
saveToPhotoAlbum: true,
correctOrientation: true,
};
Then select photos like this
this.camera.getPicture(options).then((imagePath) => {
// Special handling for Android library
if (this.platform.is('android') && sourceType ===
this.camera.PictureSourceType.PHOTOLIBRARY) { //when selecting from library
//your code goes here
} else { //when capturing by camera
//your code goes here
}

Bluetooth Serial Ionic 2

I am trying to build a simple bluetooth serial app to connect to my arduino. I am using ionic2 to make android app.right now, all I am trying to do is list all the availabe bluetooth devices. Below is my code :
import { Component } from '#angular/core';
import { BluetoothSerial } from 'ionic-native';
import { NavController } from 'ionic-angular';
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
public working:string;
public var2: string ;
bluetoothSerial.isEnabled(
function() {
this.working= "Bluetooth is enabled";
},
function() {
this.working="Bluetooth is *not* enabled";
}
);
public lists = [];
bluetoothSerial.discoverUnpaired(function(devices) {
this.lists.push(devices);
}, function(){ this.var2 = 'could not find any bluetooth device';});
constructor() { }
}
Whenever I do ionic serve I do plenty of error, mainly because Bluetooth is not recognized (function implementation is missing). It also does not allow me to build app either.
Please help on this.
Thank you so much
Looking at the docs
isEnabled()
Platforms: Android iOS Windows Phone
Reports if bluetooth is enabled
Returns: Promise returns a promise
Couple of things. You cannot call your method like that.
You should capitalize your BluetoothSerial
You should put it in a function
import { Component } from '#angular/core';
import { BluetoothSerial } from 'ionic-native';
import { NavController } from 'ionic-angular';
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
public working:string;
public var2: string ;
public lists = [];
constructor(){
this.getAlBluetoothDevices();
}
// put BluetoothSerial inside a function, can't be called different
getAllBluetoothDevices(){
// async so keep everything in this method
BluetoothSerial.isEnabled().then((data)=> {
// not sure of returning value, probably a boolean
console.log("dont know what it returns"+data);
// returns all the available devices, not just the unpaired ones
BluetoothSerial.list().then((allDevices) => {
// set the list to returned value
this.lists = allDevices;
if(!this.lists.length > 0){
this.var2 = "could not find any bluetooth devices";
}
});
});
}
}
}
The below code is for scanning the Bluetooth device
startScanning(){
this.isScanning =true;
this.bluetoothSerial.isEnabled().then(()=>{
this.bluetoothSerial.discoverUnpaired().then((allDevices)=>{
this.devices=allDevices;
this.isScanning =false;
});
});
And this code is for connecting to the device
onDeviceReady(){
let device = this.navParams.get('device');
this.bluetoothSerial.connect(device.id).subscribe((data)=>{
let alert = this.alertCtrl.create({
title: 'Bluetooth',
subTitle: data,
buttons: ['ok']
});
alert.present();
},error=>{
let alert = this.alertCtrl.create({
title: 'Bluetooth',
subTitle: error,
buttons: ['ok']
});
alert.present();
});
}
Note: It's working for me