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.
Related
I am new with Ionic 4, I am trying to check the bluetooth state with #ionic-native/diagnostic, here is my code
app.module.ts
#NgModule({
declarations: [
MyApp,
HomePage,
CheckRegInfo
],
imports: [
BrowserModule,
HttpClientModule,
TranslateModule.forRoot({
loader: {
provide: TranslateLoader,
useFactory: (createTranslateLoader),
deps: [HttpClient]
}
}),
IonicModule.forRoot(MyApp)
],
bootstrap: [IonicApp],
entryComponents: [
MyApp,
HomePage,
CheckRegInfo
],
providers: [
StatusBar,
SplashScreen,
Diagnostic,
{provide: ErrorHandler, useClass: IonicErrorHandler}
]
})
export class AppModule {}
The checking function:
import { Component } from '#angular/core';
import {AlertController, NavController} from 'ionic-angular';
import {Diagnostic} from "#ionic-native/diagnostic/ngx";
#Component({
selector: 'page-check',
templateUrl: 'check.html'
})
export class CheckRegInfo {
logowhitesrc:string = "assets/imgs/logowhite.png";
constructor(public navCtrl: NavController, private alertController:AlertController, private diagnostic: Diagnostic) {
}
checkBluetoothState(){
let titleStr: string;
this.diagnostic.getBluetoothState()
.then((state) => {
if (state == this.diagnostic.bluetoothState.POWERED_ON){
titleStr = "Okay"
} else {
titleStr = "Not Okay"
}
}).catch(e => console.error(e));
let addAlert = this.alertController.create({
title:"Bluetooth state",
message:titleStr
});
addAlert.present();
}
}
But when I try this on the device, there is no response ? I try on the ionic serve -> it going to the error Object(...) is not a function
Try the following:
declare let cordova: any;
#Component({
selector: 'page-check',
templateUrl: 'check.html'
})
export class CheckRegInfo {
logowhitesrc : string = "assets/imgs/logowhite.png";
constructor(public navCtrl : NavController,
private alertController : AlertController,
private diagnostic : Diagnostic) {}
checkBluetoothState(){
let titleStr: string;
cordova.plugins.diagnostic.getBluetoothState().then((state) => {
if (state == cordova.plugins.diagnostic.bluetoothState.POWERED_ON){
titleStr = "Okay";
showAlert(titleStr);
} else {
titleStr = "Not Okay";
showAlert(titleStr);
}
}).catch(e => console.error(e));
}
showAlert(title){
let addAlert = this.alertController.create({
title :"Bluetooth state",
message:titleStr
});
addAlert.present();
}
According to the docs, you need to call it using cordova.plugins.diagnostic:
The core plugin module is exposed via the global cordova.plugins.diagnostic object and it aliases all functions and properties of the other optional modules.
Also, since then() is used for asynchronous operation, therefore you need to call the method showAlert(titleStr) inside of .then().
I use:
nativescript 4.2
angular 6.0.0
page-router-outlet
navigation from page to page by 'lazyloading' (lateral navigation):
export const routes = [
{
path: "",
loadChildren: "~/pages/start-page/start-page.module#StartPageModule"
},
{
path: "login",
loadChildren: "~/pages/login/login.module#LoginModule"
}, ...
navigate with RouterExtensions with 'clearHistory = true'
When i navigate from page 'Home' to another page and return to 'Home' i see in memory two component 'HomeComponent'. When I repeat the operation their becomes three, four, five, .....
chrome debug window
Try to this for lazy loading routing.
app-routing.module.ts :-
import { NgModule } from "#angular/core";
import { Routes } from "#angular/router";
import { NativeScriptRouterModule } from "nativescript-angular/router";
const routes: Routes = [
{ path: "", redirectTo: "/login", pathMatch: "full" },
{ path: "startpage", loadChildren: "~/pages/start-page/start-page.module#StartPageModule" },
{ path: "login", loadChildren: "~/pages/login/login.module#LoginModule" }
]
#NgModule({
imports: [NativeScriptRouterModule.forRoot(routes)],
exports: [NativeScriptRouterModule]
})
export class AppRoutingModule { }
Redirection Code:-
import { NgZone } from "#angular/core";
import { isIOS } from "tns-core-modules/platform";
import { RouterExtensions } from "nativescript-angular/router";
constructor(private zone: NgZone,
private _routerExtensions: RouterExtensions){ }
gotoStartPage() {
setTimeout(() => {
this.zone.run(() => {
this._routerExtensions.navigate(["startpage"], {
clearHistory: (isIOS) ? true : false,
});
});
}, 500);
}
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);
});
}
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.
I have a problem in ionic 2+ menu navigation with tabs. When I click the navigation menu, how to access the child view inside the tabs view?
I found some solutions to access the tabs Rootpage but so far I couldn't access the Child view. If I push the child view Directly in app.component.ts the tabs are gone away. It will be hiding itself.
Here is my app.component.ts
import { AboutPage } from './../pages/about/about';
import { Component, ViewChild } from '#angular/core';
import { Events, MenuController, Nav, Platform, NavController } from 'ionic-angular';
import { SplashScreen } from '#ionic-native/splash-screen';
import { App } from 'ionic-angular';
import { ConferenceData } from '../providers/conference-data';
import { UserData } from '../providers/user-data';
export interface PageInterface {
title: string;
name: string;
component: any;
icon: string;
logsOut?: boolean;
index?: number;
tabName?: string;
tabComponent?: any;
}
#Component({
templateUrl: 'app.template.html'
})
export class TestApp {
#ViewChild(Nav) nav: Nav;
#ViewChild('mycontent') childNavCtrl: NavController;
appPages: PageInterface[] = [
{ title: 'ABOUT US', name: 'TabsPage', component: TabsPage, tabComponent: AboutPage, index: 3, icon: 'assets/img/about-small.png' },
];
rootPage: any;
constructor(
public events: Events,
public userData: UserData,
public menu: MenuController,
public platform: Platform,
public confData: ConferenceData,
public storage: Storage,
public splashScreen: SplashScreen,
public appCtrl: App,
) {
}
openPage(page: PageInterface) {
let params = {};
if (page.index != null) {
params = { tabIndex: page.index };
}
if (this.nav.getActiveChildNavs() && page.index != undefined) {
// push the view here //
} else {
alert('else');
this.nav.setRoot(page.name, params).catch((err: any) => {
console.log(`Didn't set nav root: ${err}`);
});
}
Here is my app.modules.ts
#NgModule({
declarations: [
testApp,
AboutPage,
AccountPage,
LoginPage
],
imports: [
BrowserModule,
HttpModule,
IonicModule.forRoot(testApp, {}, {
links: [
{ component: TabsPage, name: 'TabsPage', segment: 'tabs-page' },
{ component: GalleryDetailsPage, name: 'Gallery details', segment: 'gallery Details' },
{ component: AboutPage, name: 'About', segment: 'about' },
]
}),
CloudModule.forRoot(cloudSettings),
IonicStorageModule.forRoot()
],
bootstrap: [IonicApp],
entryComponents: [
testApp,
AboutPage,
],
providers: [
{ provide: ErrorHandler, useClass: IonicErrorHandler },
ConferenceData,
UserData,
SocialSharing,
InAppBrowser,
Geolocation,
PostPage,
ImagePicker,
Camera,
SplashScreen
]
})
export class AppModule { }
here is my my app.template.html
<ion-content class="menu-contents">
<ion-list class="menu-con">
<button ion-item class="cus-item" menuClose *ngFor="let p of appPages" (click)="openPage(p)">
<!-- ion-icon item-start [name]="p.icon" [color]="isActive(p)"></ion-icon -->
<img [src]="p.icon" class="menu-item-img {{p.title === 'POST' ? 'post-icon' : ''}}" alt=""><span class="menu-item-title">{{p.title}}</span>
</button>
</ion-list>
</ion-content>
here is my tabs page:
import { HomePage } from '../home/home';
import { Component } from '#angular/core';
import { NavParams, MenuController, NavController } from 'ionic-angular';
import { AboutPage } from '../about/about';
import { SchedulePage } from '../dash/schedule';
#Component({
selector : 'tabs-view',
templateUrl: 'tabs-page.html'
})
export class TabsPage {
// set the root pages for each tab
tab1Root:any;
tab2Root: any = SchedulePage;
tab3Root: any = AboutPage;
mySelectedIndex: number;
constructor(
navParams: NavParams,
public menu: MenuController,
public navCtrl: NavController,
) {
this.tab1Root = HomePage;
console.log('ONE', navParams.data);
if (navParams.data.tabIndex != null) {
}
}
ionViewDidLoad() {
this.menu.enable(true);
}
}
here is my tabs.html:
<ion-tabs [selectedIndex]="mySelectedIndex" name="weddingapp" #myTabs>
<ion-tab [root]="tab1Root" tabTitle="" tabIcon="icon-home"></ion-tab>
<ion-tab [root]="tab2Root" tabTitle="" tabIcon="icon-dash"></ion-tab>
<ion-tab [root]="tab3Root" tabTitle="" tabIcon="icon-user" class="custom-icon1">user</ion-tab>
Here is my Shedulepage.ts
#Component({
selector: 'page-schedule',
templateUrl: 'schedule.html'
})
export class SchedulePage {
#ViewChild('scheduleList', { read: List }) scheduleList: List;
constructor(
public alertCtrl: AlertController,
public app: App,
public loadingCtrl: LoadingController,
public modalCtrl: ModalController,
public navCtrl: NavController,
public toastCtrl: ToastController,
public confData: ConferenceData,
public user: UserData,
public menu: MenuController,
navParams: NavParams,
) {
console.log(navParams.data);
}
GotoLinks(val:any){
this.navCtrl.push(ContactPage);
}
If you want to push inside the child then what I have is
import { NavController} from 'ionic-angular';
constructor(public navCtrl: NavController){}
myFunction(){
this.navCtrl.push(SomePage);
}
If you want to push inside the tab page
import { App} from 'ionic-angular';
constructor(public app: App){}
myFunction(){
this.app.getRootNav().push(SomePage);
}