Events in Ionic v4 - ionic-framework

I'm using Ioni v4Beta and I'm traying to update the sidemenu when the user is login.
I search but the usual solution is use Events:
Ionic 3 refresh side menu after login
https://ionicframework.com/docs/api/util/Events/
But in the new version I don't find it, and I don't know how to do it
https://beta.ionicframework.com/docs/api

Thanks a lot, but I finally find how to import it:
import { Events } from '#ionic/angular';

Example on how to do it with subjects:
export const someEvent:Subject = new Subject();
export class ReceivingClass implements OnDestroy, OnInit
{
private someEventSubscription:Subscription;
public OnInit():void{
someEventSubscription = someEvent.subscribe((data) => console.log(data);
}
public onDestroy():void{
someEvent.unsubscribe();
}
}
export class SendingClass implements OnInit
{
public OnInit():void{
setTimeout(() => {
someEvent.next('hi');
}, 500);
}
}

Are you aware that Ionic v4 events will be deprecated soon?
I was also trying to update the sidemenu when a user logs in as well, so i tried using: import { Events } from '#ionic/angular';
However I got a warning referring me to this link https://angular.io/guide/observables#basic-usage-and-terms which I failed to follow because am not that familiar with observables.
After much research I found that I can still use events but I had to import them from angular's router directive.
This was my code before:
/* import was */
import { Events } from '#ionic/angular';
import { Storage } from '#ionic/storage';//ignore this import if doesn't apply to your code
/* inside the class */
constructor(
private events: Events,
private storage: Storage
) {
this.events.subscribe("updateMenu", () => {
this.storage.ready().then(() => {
this.storage.get("userLoginInfo").then((userData) => {
if (userData != null) {
console.log("User logged in.");
let user = userData.user;
console.log(user);
}
else {
console.log("No user found.");
let user = {};
}
}).catch((error)=>{
console.log(error);
});
}).catch((error)=>{
console.log(error);
});
});
}
changes i made that actually got my code working and deprecation warning gone:
/* import is now */
import { Router,RouterEvent } from '#angular/router';
import { Storage } from '#ionic/storage';//ignore this import if it does't apply to your code
Rest of code
constructor(
public router: Router,
public storage: Storage
){
this.router.events.subscribe((event: RouterEvent) => {
this.storage.ready().then(() => {
this.storage.get("userLoginInfo").then((userData) => {
if (userData != null) {
/*console.log("User logged in.");*/
let user = userData.user;
/*console.log(this.user);*/
}
else {
/*console.log("No user found.");*/
let user = {};
}
}).catch((error)=>{
console.log(error);
});
}).catch((error)=>{
console.log(error);
});
});
}
I got the idea after seeing this https://meumobi.github.io/ionic/2018/11/13/side-menu-tabs-login-page-ionic4.html. I hope my answer can be useful.

Steps to resolve the issue
import events in login page and in sidemenu view
In login page, after login success do your logic to publish the events.
for eg:
this.authService.doLogin(payload).subscribe((response) => {
if (response.status) {
this.storage.set('IS_LOGGED_IN', true);
this.events.publish('user:login');
}
}, (error) => {
console.log(error);
});
In sidemenu view, create a listener to watch the events 'user:login'
for eg:
this.menus = [];
// subscribe events
this.events.subscribe('user:login', () => {
// DO YOUR LOGIC TO SET THE SIDE MENU
this.setSidemenu();
});
// check whether the user is logged in or not
checkIsUserloggedIn() {
let isLoggedIn = false;
if (this.storage.get('IS_LOGGED_IN') == '' ||
this.storage.get('IS_LOGGED_IN') == null ||
this.storage.get('IS_LOGGED_IN') == undefined) {
isLoggedIn = false;
} else {
isLoggedIn = true;
}
return isLoggedIn;
}
// to set your sidemenus
setSidemenu() {
let isUserLoggedIn = this.checkIsUserloggedIn();
if(isUserLoggedIn) {
this.menus = ['Home', 'Aboutus', 'Contactus', 'My Profile', 'Logout'];
} else {
this.menus = ['Login', 'Home', 'Aboutus', 'Contactus'];
}
}

Related

PushNotifications stop working after installing Community/FCM plugin

I am currently using ionic capacitor PushNotifications for Firebase cloud messaging. By the help of this I can get tokens.
Now I want to send notifications to all app users so I decided to use topics.
For this, I installed community/FCM plugin.
capacitor-community/fcm
I also made suggested changes in the MainActivity.java file, no error during app build.
But after installation this FCM plugin, PushNotifications(token) stop working.
Even below code starts always retuning false.
if (isPushNotificationsAvailable) {
this.initPushNotifications();
}
Here is my MainActivity.java file:-
package io.ionic.starter;
import com.getcapacitor.community.fcm.FCMPlugin;
import android.os.Bundle;
import com.getcapacitor.BridgeActivity;
import com.getcapacitor.Plugin;
import java.util.ArrayList;
public class MainActivity extends BridgeActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Initializes the Bridge
this.init(savedInstanceState, new ArrayList<Class<? extends Plugin>>() {{
// Additional plugins you've installed go here
// Ex: add(TotallyAwesomePlugin.class);
add(FCMPlugin.class);
}});
}
}
Here my fcm.service.ts File:-
import { Component, Injectable } from '#angular/core';
import { Capacitor } from '#capacitor/core';
import { Router } from '#angular/router';
import { Storage } from '#ionic/storage';
import {
ActionPerformed,
PushNotificationSchema,
PushNotifications,
Token
} from '#capacitor/push-notifications';
// import { FCM } from '#capacitor-community/fcm';
const isPushNotificationsAvailable = Capacitor.isPluginAvailable('PushNotifications');
#Injectable({
providedIn: 'root'
})
export class FcmService {
public topicName = 'project';
constructor(
private router: Router,
private storage: Storage
) { }
initPush() {
//This Plugin is not available on web
if (isPushNotificationsAvailable) {
this.initPushNotifications();
}
}
// Request permission to use push notifications
// iOS will prompt user and return if they granted permission or not
// Android will just grant without prompting
private initPushNotifications() {
//console.log('Initializing HomePage');
PushNotifications.requestPermissions().then(result => {
if (result.receive === 'granted') {
// Register with Apple / Google to receive push via APNS/FCM
PushNotifications.register();
} else {
// Show some error
}
});
PushNotifications.addListener('registration', (token: Token) => {
alert('Push registration success, token: ' + token.value);
//Store Devive Token in session variable
this.storage.set("device_token", token.value);
// FCM.getToken()
// .then((r) => alert(`Token ${r.token}`))
// .catch((err) => console.log(err));
// now you can subscribe to a specific topic
// FCM.subscribeTo({ topic: this.topicName })
// .then((r) => alert(`subscribed to topic`))
// .catch((err) => console.log(err));
});
PushNotifications.addListener('registrationError', (error: any) => {
//alert('Error on registration: ' + JSON.stringify(error));
});
PushNotifications.addListener(
'pushNotificationReceived',
(notification: PushNotificationSchema) => {
//alert('Push received: ' + JSON.stringify(notification));
},
);
PushNotifications.addListener(
'pushNotificationActionPerformed',
(notification: ActionPerformed) => {
// alert('Push action performed: ' + JSON.stringify(notification));
const data = notification.notification.data;
//console.log('Action performed: ' + JSON.stringify(notification.notification));
if (data.detailsId) {
this.router.navigate(['/bid-project', data.detailsId]);
}
},
);
}
//Reset all Badge count
// resetBadgeCount() {
// PushNotifications.removeAllDeliveredNotifications();
// }
// move to fcm demo
// subscribeTo() {
// PushNotifications.register()
// .then((_) => {
// FCM.subscribeTo({ topic: this.topicName })
// .then((r) => alert(`subscribed to topic ${this.topicName}`))
// .catch((err) => console.log(err));
// })
// .catch((err) => alert(JSON.stringify(err)));
// }
// unsubscribeFrom() {
// FCM.unsubscribeFrom({ topic: this.topicName })
// .then((r) => alert(`unsubscribed from topic ${this.topicName}`))
// .catch((err) => console.log(err));
// }
}
After removing community plugin token generation started working as before.
Please tell me what wrong is with my code.

Create a common loader by intercepting http request (HttpInterceptors)

I am creating a common loader in ionic 3 but there is a problem because of manually using loader.dismiss()
Instead of creating a loader using loaderCtrl on very http request in ionic I'm planning to make only one loader. I am using a httpInterceptor and when the request is intercepted i created and present the loader. And i check if the event is of type HttpRequest, if yes the loader is dismissed.
This works fine when only http request is made on any page i.e the request is made it is intercepted the loader is presented later when the response is obtained the loader is dismissed.
But now if there are 2 request made on 1 page i gate the error of removeView not Found.
/loaderInterceptor.ts
#Injectable()
export class HttpLoaderInterceptor implements HttpInterceptor {
headersConfig: any;
loader: any
constructor(public loadingCtrl: LoadingController) { }
intercept(req: HttpRequest<any>, next: HttpHandler):
Observable<HttpEvent<any>> {
this.loader = this.loadingCtrl.create({
content: "Please wait",
});
this.loader.present()
return next.handle(req).pipe(tap((event: HttpEvent<any>) => {
if (event instanceof HttpResponse) {
this.loader.dismiss();
}
},
(err: any) => {
this.loader.dismiss();
}));
}
}
The dismiss method is called twice as 2 response are obtained and the 2nd time there is no loader to be dismissed so we get an error.
Please help.
In my think, the request success before loading bar reason, so I created one service use to solve it. My source code is below:
import { Injectable } from '#angular/core';
import { LoadingController } from '#ionic/angular';
#Injectable({
providedIn: 'root'
})
export class LoadingService {
private loaders = [];
private badLoaders = 0;
constructor(
private loadingController: LoadingController
) {
}
async startLoading() {
if (this.badLoaders > 0) {
this.badLoaders --;
} else {
await this.loadingController.create({
message: 'Loading ...',
}).then(loader => {
this.loaders.push(loader);
loader.present().then(() => {
if (this.badLoaders > 0) {
this.badLoaders --;
this.endLoading();
}
});
});
}
}
endLoading() {
let loader = this.loaders.pop();
if (loader) {
loader.dismiss();
} else {
this.badLoaders ++;
}
}
}
You can try it, use LoadingService.startLoading instead this.loadingCtrl.create and LoadingService.endLoading instead this.loader.dismiss();.

IONIC-3 NavController throwing can't resolve all parameters error

I have an interesting problem with IONIC-3 that I've not been able to solve. I am attempting to implement an auth routing which is triggered by ionViewCanEnter. However, while I can pass one nav setter, it will not allow multiple. Here is the code:
AuthService Function:
isAuthenticated(nav: NavController): boolean | Promise<any> {
const userAuth = this.uData.getAuthenticated;
const userProfile = this.uData.getUserProfile;
if (userAuth ) {
//User is logged in, so let's check a few things.
if (!userProfile.sign_up_complete) {
//User has not completed sign up
setTimeout(() => { nav.setRoot(CreateAccountPage) }, 0);
}
return true
} else {
//User is not authenticated, return to walkthrough
setTimeout(() => { nav.setRoot(WalkthroughPage) }, 0);
return false
}}
Example calling:
ionViewCanEnter(): boolean | Promise<any> {
return this.auth.isAuthenticated(this.nav);
}
If I have only CreateAccountPage, the script runs fine. However, when I add WalkthroughPage, it throws the following error:
Error: Can't resolve all parameters for ListingPage: (?, [object Object], [object Object], [object Object]).
Which is an error related to the AuthService. For clarity the WalkthroughPage code is as follows:
import { Component, ViewChild } from '#angular/core';
import { IonicPage, NavController, Slides } from 'ionic-angular';
import { RemoteConfigProvider } from '../../providers/remote-config/remote-config';
import { LoginPage } from '../login/login';
import { SignupPage } from '../signup/signup';
#IonicPage()
#Component({
selector: 'walkthrough-page',
templateUrl: 'walkthrough.html'
})
export class WalkthroughPage {
lastSlide = false;
sign_up_enabled: null;
sign_in_enabled: null;
#ViewChild('slider') slider: Slides;
constructor(public nav: NavController,
public remoteConfig: RemoteConfigProvider) {
}
ionViewDidLoad() {
this.remoteConfig.getValue('sign_up_enabled').then(t => {
this.sign_up_enabled = t;
})
this.remoteConfig.getValue('sign_in_enabled').then(t => {
this.sign_in_enabled = t;
})
}
skipIntro() {
this.lastSlide = true;
this.slider.slideTo(this.slider.length());
}
onSlideChanged() {
this.lastSlide = this.slider.isEnd();
}
goToLogin() {
this.nav.push(LoginPage);
}
goToSignup() {
this.nav.push(SignupPage);
}
}
I have attempted to compare both pages, but not identified the exact cause. I welcome any thoughts.
For those who encounter a similar issue, the fix was straight forward. I simply used deep-linking reference which resolved all issues. Example below.
isAuthenticated(nav: NavController): boolean | Promise<any> {
const userAuth = this.userStore.getAuthenticated;
const userProfile = this.userStore.getUserProfile;
if (userAuth) {
return true
} else {
console.log('Auth guard: Not authenticated');
setTimeout(() => { nav.setRoot('no-access') }, 0);
return false
}
}

Ionic3 framework network.onConnect().subscribe not working?

I have created a little phone app with Ionic. I am trying to implement a bit logic where the component knows when its online or offline. To do so I am using the network plugin fom Ionic and it just does not work as expected.
instead of updating the
this.connected
value every time when I switch on / off the network, it will only do so if I switch it off / on AND do something like switching from landscape to portrait mode, or work on a different app for a while and come back to the app.
Really puzzled by that.
Here is the code:
import {Component} from '#angular/core';
import {NavController, NavParams, Platform} from 'ionic-angular';
import {GooglePlus} from '#ionic-native/google-plus';
import {SurveyService} from "./survey.service";
import {Survey} from "../../Declarations/Survey";
import {SurveyPage} from "../survey/survey";
import {Network} from "#ionic-native/network";
#Component({
selector: 'page-home',
templateUrl: 'home.html',
providers: [SurveyService, Network]
})
export class HomePage {
public surveys: Survey[] = [];
public connected;
public networkType;
constructor(public navCtrl: NavController,
private googlePlus: GooglePlus,
private surveyService: SurveyService,
public navParams: NavParams,
platform: Platform,
private network: Network) {
this.checkForNetwork();
this.surveyService.getAvailable().subscribe(surveys => {
this.checkForNetwork();
this.surveys = surveys;
})
}
login() {
this.googlePlus.login({
'webClientId': '632130231957-dmjd154jhq1eenimedri3m0de6sh7tln.apps.googleusercontent.com'
}).then((res) => {
console.log(res);
}, (err) => {
console.log(err);
});
}
logout() {
this.googlePlus.logout().then(() => {
console.log("logged out");
});
}
openSurvey = (survey: Survey) => {
this.navCtrl.push(SurveyPage, {
survey: survey
});
}
checkForNetwork = () => {
this.networkType= this.network.type;
this.network.onDisconnect().subscribe(() => {
this.connected = false;
this.network.type = null;
});
this.network.onConnect().subscribe(() => {
this.connected = 'network connected!';
setTimeout(() => {
if (this.network.type === 'wifi') {
this.connected = true;
}
}, 3000);
});
}
}
OK, I worked it out:
Turns out that ionic works perfectly fine, but I tried to change the view of my application depending on whether
this.connected
is true or false. I did not realize that I needed to tell Angular to refresh its view by using Application
applicationRef.tick();
in the right place. So basically, once the Ionic changes the value of this.connected you need to tell Angular about it, here is the corrected part of the code:
You need to inject ApplicationRef into the constructor
constructor(public navCtrl: NavController,
...
private appReference: ApplicationRef) {
...
checkForNetwork = () => {
this.networkType= this.network.type;
this.network.onDisconnect().subscribe(() => {
this.connected = false;
this.network.type = null;
this.appReference.tick();
});
this.network.onConnect().subscribe(() => {
this.connected = 'network connected!';
setTimeout(() => {
if (this.network.type === 'wifi') {
this.connected = true;
this.appReference.tick();
}
}, 3000);
});
}

ionic push notification when app is in foreground

I am making a ionic 3 app. I want notifications to appear even when app is in foreground. I have tried using FCM Plugin I'm getting notifications only when app is in background.
Home.ts
import { AngularFireDatabase } from 'angularfire2/database';
import { Component } from '#angular/core';
import { NavController } from 'ionic-angular';
import firebase from 'firebase';
declare var FCMPlugin;
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
firestore = firebase.database().ref('/pushtokens');
firemsg = firebase.database().ref('/messages');
constructor(public navCtrl: NavController,public afd:AngularFireDatabase) {
this.tokensetup().then((token)=>{
this.storeToken(token);
})
}
ionViewDidLoad() {
FCMPlugin.onNotification(function (data) {
if (data.wasTapped) {
//Notification was received on device tray and tapped by the user.
alert(JSON.stringify(data));
} else {
//Notification was received in foreground. Maybe the user needs to be notified.
alert(JSON.stringify(data));
}
});
FCMPlugin.onTokenRefresh(function (token) {
alert(token);
});
}
tokensetup(){
var promise = new Promise((resolve,reject)=>{
FCMPlugin.getToken(function(token){
resolve(token);
},(err)=>{
reject(err);
});
})
return promise;
}
storeToken(token){
this.afd.list(this.firestore).push({
uid: firebase.auth().currentUser.uid,
devtoken: token
}).then(()=>{
alert('Token stored')
}).catch(()=>{
alert('Token not stored');
})
// this.afd.list(this.firemsg).push({
// sendername:'adirzoari',
// message: 'hello for checking'
// }).then(()=>{
// alert('Message stored');
// }).catch(()=>{
// alert('message not stored');
// })
}
}
the function cloud for notifications
var functions = require('firebase-functions');
var admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
var wrotedata;
exports.Pushtrigger = functions.database.ref('/messages/{messageId}').onWrite((event) => {
wrotedata = event.data.val();
admin.database().ref('/pushtokens').orderByChild('uid').once('value').then((alltokens) => {
var rawtokens = alltokens.val();
var tokens = [];
processtokens(rawtokens).then((processedtokens) => {
for (var token of processedtokens) {
tokens.push(token.devtoken);
}
var payload = {
"notification":{
"title":"From" + wrotedata.sendername,
"body":"Msg" + wrotedata.message,
"sound":"default",
},
"data":{
"sendername":wrotedata.sendername,
"message":wrotedata.message
}
}
return admin.messaging().sendToDevice(tokens, payload).then((response) => {
console.log('Pushed notifications');
}).catch((err) => {
console.log(err);
})
})
})
})
function processtokens(rawtokens) {
var promise = new Promise((resolve, reject) => {
var processedtokens = []
for (var token in rawtokens) {
processedtokens.push(rawtokens[token]);
}
resolve(processedtokens);
})
return promise;
}
it works only when the app in the background. but when i exit from the app and it's not in the background I don't get any notification.
You need to edit the FCM Plugin files. I found the solution only for android now.
I use https://github.com/fechanique/cordova-plugin-fcm this FCM plugin for android and ios in cordova.
You need to edit file MyFirebaseMessagingService.java line 53(line no be may be differ).
In this file there is a method onMessageReceived at the end of the method there is a line which is commented, this line calling an another method i.e. sendNotification(....).
sendNotification(remoteMessage.getNotification().getTitle(), remoteMessage.getNotification().getBody(), data);
You have to uncomment this line and change last parameter from remoteMessage.getData() to data (data variable is already there in the code).
And comment this line FCMPlugin.sendPushPayload( data );
Now you are good to go. Now you are able to receive notification even when app is opened (foreground), you will receive the banner (floating) notifications.
If you found anything for IOS please let me know!!!
I am using firebase plugin for ionic 3.
There is a check if notification data contain "notification_foreground" or not and save it in variable foregroundNotification.
if(data.containsKey("notification_foreground")){
foregroundNotification = true;
}
then it create showNotification variable which decide if we need to show notification or not and pass this to the sendMessage (show notification function).
if (!TextUtils.isEmpty(body) || !TextUtils.isEmpty(title) || (data != null && !data.isEmpty())) {
boolean showNotification = (FirebasePlugin.inBackground() || !FirebasePlugin.hasNotificationsCallback() || foregroundNotification) && (!TextUtils.isEmpty(body) || !TextUtils.isEmpty(title));
sendMessage(data, messageType, id, title, body, showNotification, sound, vibrate, light, color, icon, channelId, priority, visibility);
}
your payload should contain notification_foreground, notification_title and notification_body.