I am trying to overwrite the navigation back button to my needs in android using ionic 3 but whenever i run my app it shows an error when i press back navigation button saying "nav.getActive is not a function" due to this back button doesn't work.
Updated Code is as followed
export class MyApp {
rootPage:any = LoginPage;
public counter=0;
#ViewChild(Nav) nav: Nav;
constructor(platform: Platform, statusBar: StatusBar, splashScreen: SplashScreen,public globalProvider: GlobalProvider,
public googlePlus: GooglePlus, public zone: NgZone, private readonly firebase: Firebase, private alertCtrl: AlertController,
public toastCtrl: ToastController, public app: App) {
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();
platform.registerBackButtonAction(() => {
const activeView = this.nav.getActive().name // This will give you the activeview name
if(activeView === 'HomePage') {
if (this.nav.canGoBack()){ //Can we go back?
this.nav.pop();
} else {
const alert = this.alertCtrl.create({
title: 'App termination',
message: 'Do you want to close the app?',
buttons: [{
text: 'Cancel',
role: 'cancel',
handler: () => {
console.log('Application exit prevented!');
}
},{
text: 'Close App',
handler: () => {
platform.exitApp(); // Close this application
}
}]
});
alert.present();
}
}
this.nav.push(TabsPage);
}, 1);
this.firebase.onNotificationOpen().subscribe(notification => {
console.log('notification info: ', notification);
/*!notification.tap
? console.log('The user was using the app when the notification arrived...')
: console.log('The app was closed when the notification arrived...');
let notificationAlert = this.alertCtrl.create({
title: notification.title,
message: notification.body,
buttons: ['Ok']
});
notificationAlert.present();*/
},
error => {
console.error('Error getting the notification', error);
});
});
/*platform.registerBackButtonAction(() => {
if (this.counter == 0) {
this.counter++;
this.presentToast();
setTimeout(() => { this.counter = 0 }, 3000)
} else {
// console.log("exitapp");
platform.exitApp();
}
}, 0) });*/
}
Try like this.
#ViewChild(Nav) nav: Nav;
constructor(platform: Platform,
statusBar: StatusBar,
splashScreen: SplashScreen,
public globalProvider: GlobalProvider,
public toastCtrl: ToastController,
public googlePlus: GooglePlus,
public zone: NgZone,
public app: App,
public alertCtrl: AlertController
) {
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();
platform.registerBackButtonAction(() => {
**const activeView = this.nav.getActive().name** // This will give you the activeview name
if(active.instance instanceof HomePage) {
if (nav.canGoBack()){ //Can we go back?
nav.pop();
} else {
const alert = this.alertCtrl.create({
title: 'App termination',
message: 'Do you want to close the app?',
buttons: [{
text: 'Cancel',
role: 'cancel',
handler: () => {
console.log('Application exit prevented!');
}
},{
text: 'Close App',
handler: () => {
platform.exitApp(); // Close this application
}
}]
});
alert.present();
}
}
nav.push(HomePage);
}, 100);
});
}
Related
It's a simple alertController box, which create a checklist element. When I click on add, the function addCheck() of the class ChecksPage is called :
export class ChecksPage implements OnInit {
checkList: Check[] = [];
constructor(private alertCtrl: AlertController) { }
ngOnInit() {
}
addCheck(){
this.alertCtrl.create({
header: 'Nouvelle liste',
inputs:[{
name:'nom',
placeholder: 'Nom'
}],
buttons:[
{
text: 'Annuler',
role: 'cancel'
},
{
text: 'Ajouter',
handler: data => {
if(typeof data.nom !=null){
let newCheck: Check;
newCheck.id = ''+this.checkList.length;
newCheck.title = data.nom;
this.checkList.push(newCheck);
}
}
}]
}).then(alertEl => alertEl.present());
}
}
But, I have an error : the variable newCheck is undefined. Why ?
Check is an interface :
export interface Check{
id: string;
title: string;
}
You didn't init your variable, please do as follow:
const newCheck = {
id: ''+this.checkList.length,
title: data.nom
} as Check;
According to the documentation https://ionicframework.com/docs/api/toast :
Dismissing The toast can be dismissed automatically after a specific
amount of time by passing the number of milliseconds to display it in
the duration of the toast options. If a button with a role of "cancel"
is added, then that button will dismiss the toast. To dismiss the
toast after creation, call the dismiss() method on the instance.
But in the following code (from the same doc) both the CLOSE and FAVORITE buttons lead to the dismiss of the toast (and of course the call of toast.onDidDismiss()). But Only the CLOSE one has the role 'cancel'.
I would like to have a button and perform an action without closing the Toast, am I missing something ?
import { Component } from '#angular/core';
import { ToastController } from '#ionic/angular';
#Component({
selector: 'toast-example',
templateUrl: 'toast-example.html',
styleUrls: ['./toast-example.css'],
})
export class ToastExample {
constructor(public toastController: ToastController) {}
async presentToast() {
const toast = await this.toastController.create({
message: 'Your settings have been saved.',
duration: 2000
});
toast.present();
}
async presentToastWithOptions() {
const toast = await this.toastController.create({
header: 'Toast header',
message: 'Click to Close',
position: 'top',
buttons: [
{
side: 'start',
icon: 'star',
text: 'Favorite',
handler: () => {
console.log('Favorite clicked');
}
}, {
text: 'Done',
role: 'cancel',
handler: () => {
console.log('Cancel clicked');
}
}
]
});
await toast.present();
const { role } = await toast.onDidDismiss();
console.log('onDidDismiss resolved with role', role);
}
}
Setting the role to something other than null or 'cancel', and returning false on the handler() should do what you need.
Example:
//...
buttons: [
{
icon: "copy-outline",
role: "copy",
handler: () => {
console.log("copied!");
return false;
}
}]
//...
Im using navigation control in ionic provider whenever i triggered the provider it shows the runtime error Cannot read property 'pop' of null
my code is
#Injectable()
export class ServerResponseProvider {
#ViewChild('myContent') navCtrl: NavController;
constructor(public http: Http, public alertCtrl: AlertController,
protected injector: Injector, private app:App) {
console.log('Hello ServerResponseProvider Provider');
}
httpGetRes(url) {
return Observable.create(observer => {
this.http.get(url)
.map(res => res.json())
.subscribe(data => {
console.log("response:", data);
observer.next(data);
}, (err) => {
console.log("Your error : ", err);
observer.error(err);
if (err.status == 400) {
this.alertC('Validation Error');
} else if (err.status == 403) {
this.alertC('Authorization error')
} else if (err.status == 500) {
this.alertC('Something went wrong try again later')
}
});
});
}
alertC(msg) {
let alert = this.alertCtrl.create({
title: ' OOPS !!!!',
subTitle: msg,
buttons: [{
text: 'ok',
handler: () => {
this.navCtrl.pop();
}
}]
});
alert.present(alert);
}
}
i tried in many ways it wont works
thanks in advance
How to go to a specific page when clicking on a notification?
I use Firebase console to push the notification
I used like this. but it didn't work
fcm.onNotification().subscribe(data=>{
if(data.wasTapped){
this.navcntrl.push(MessagePage);
};
})
How i can do it correctly?
My full code: app.component.ts
export class MyApp {
#ViewChild(Nav) nav: Nav;
rootPage: any = HomePage;
pages: Array<{title: string, component: any}>;
constructor(public platform: Platform,private fcm: FCM, public statusBar: StatusBar, public splashScreen: SplashScreen) {
fcm.onNotification().subscribe(data=>{
this.nav.push(ListPage)
})
this.initializeApp();
this.pages = [
{ title: 'Home', component: HomePage },
{ title: 'List', component: ListPage }
];
}
initializeApp() {
this.platform.ready().then(() => {
this.statusBar.styleDefault();
this.splashScreen.hide();
});
}
openPage(page) {
this.nav.setRoot(page.component);
}
}
Thanks in advance
I solve this issue.
You have to add the property “click_ action”: “FCM_PLUGIN_ACTIVITY” to the “notification” object in order to properly use the background method.
Example:
{
"to" : "tokenHere",
"notification" : {
"title": "title",
"body" : "message",
"sound": "default",
"click_action":"FCM_PLUGIN_ACTIVITY"
},
"data": {
"content": "whatever",
},
"priority":"high"
}
and use FCM API. Don’t use firebase console.
I want to exit the app when the device have no internet connection, but I use exitApp it nothing happened, here is my code:
constructor(platform: Platform, statusBar: StatusBar, splashScreen: SplashScreen, private alertCtrl: AlertController, private network: Network, public deeplinks: Deeplinks, public events: Events) {
platform.ready().then(() => {
let disconnectSub = this.network.onDisconnect().subscribe(() => {
console.log('you are offline');
});
let connectSub = this.network.onConnect().subscribe(()=> {
console.log('you are online');
});
if(this.network.type === 'none' || this.network.type === 'unknown') {
let alert = this.alertCtrl.create({
title: "Internet Connection Problem",
subTitle:"Please Check Your Network connection",
buttons: [{
text: 'Ok',
handler: () => {
platform.exitApp();
}
}]
});
alert.present();
}
});
}
Anyone have experience before? Thanks.