Tabbar is not hided on subpages in Ionic 5 - ionic-framework

In ionic 4 or 5, tabbar is not hided on subpages.
Of course, it works well in ionic 2 or 3.
Please let me know how to solve this issue.

This is my solution.
But hope the best solution.
create TabsService
import this in app.module.ts
Here is full code of TabsService
import { Injectable } from '#angular/core';
import { filter } from 'rxjs/operators';
import { NavigationEnd, Router } from '#angular/router';
import { Platform } from '#ionic/angular';
#Injectable({
providedIn: 'root'
})
export class TabsService {
constructor(private router: Router, private platform: Platform) {
this.platform.ready().then(() => {
this.navEvents();
});
}
public hideTabs() {
const tabBar = document.getElementById('kidesiaTabBar');
if (tabBar && tabBar.style.display !== 'none') {
tabBar.style.display = 'none';
}
}
public showTabs() {
const tabBar = document.getElementById('kidesiaTabBar');
if (tabBar && tabBar.style.display !== 'flex') {
tabBar.style.display = 'flex';
}
}
private navEvents() {
this.router.events
.pipe(filter(e => e instanceof NavigationEnd))
.subscribe((e: any) => {
this.showHideTabs(e);
});
}
private showHideTabs(e: any) {
const urlArray = e.url.split('/');
if (urlArray.length >= 3) {
let shouldHide = true;
if (urlArray.length === 3 && urlArray[1] === 'tabs') {
shouldHide = false;
}
try {
setTimeout(() => (shouldHide ? this.hideTabs() : this.showTabs()), 300);
} catch (err) {}
}
}
}

Related

Rest web service returns null value on mobile device but works on PC in Ionic App

i am consuming Rest JSONP Web Service in an ionic App which works fine on PC but returns null value on mobile devices
My page.ts file
import {
Component,
OnInit
} from '#angular/core';
import {
AlertController,
LoadingController
} from '#ionic/angular';
import {
ActionSheetController
} from '#ionic/angular';
import {
Router
} from '#angular/router'
import {
ProApiService
} from './../../../../services/pro-api.service';
#Component({
selector: 'app-ranked-diagnosis',
templateUrl: './ranked-diagnosis.page.html',
styleUrls: ['./ranked-diagnosis.page.scss'],
})
export class RankedDiagnosisPage implements OnInit {
tabSelect: string = 'show10';
show10Data: Array < any >= [];
showAllData: Array < any >= [];
redFlagsData: Array < any >= [];
loading: any;
constructor(
private api: ProApiService,
public alertController: AlertController,
public loadingController: LoadingController,
public actionSheetController: ActionSheetController,
private router: Router
) {}
segmentChanged(event: any) {
this.tabSelect = event.detail.value;
}
async presentActionSheet(buttons) {
const actionSheet = await this.actionSheetController.create({
header: 'Sub Diagnosis',
buttons: buttons
});
await actionSheet.present();
}
async presentAlert(msg: string, header: string) {
const alert = await this.alertController.create({
header: '',
subHeader: header,
message: msg,
buttons: ['OK']
});
await alert.present();
}
async presentLoading() {
this.loading = await this.loadingController.create({
message: 'loading...',
});
return await this.loading.present();
}
ngOnInit() {
}
ionViewWillEnter() {
if (this.api.ProApiData.diagnoses_checklist.diagnoses) {
this.showAllData =
this.api.ProApiData.diagnoses_checklist.diagnoses;
for (let i = 0; i < 10; i++) {
this.show10Data.push(this.showAllData[i]);
}
this.showAllData.forEach(item => {
if (item.red_flag == 'true') {
this.redFlagsData.push(item);
}
});
console.log(this.showAllData);
} else {
console.log('error');
this.router.navigateByUrl('isabel-pro');
}
}
why_diagnosis(url: any, weightage: any) {
this.presentLoading();
this.api.why_diagnosisApi(url).subscribe(res => {
let matched_terms = res._body.why_diagnosis.matched_terms;
console.log(matched_terms);
let alertMsg = `We matched the terms: ${matched_terms}<br><hr>Degree of match between query entered and database: ${weightage}`;
this.presentAlert(alertMsg, 'Why did this diagnosis come up ?');
this.loadingController.dismiss();
}, err => {
this.loadingController.dismiss();
console.log('error');
});
}
}
in the above code i am calling why_diagnosis function which calls the function from a service file.
My service.ts file
import {
Injectable
} from '#angular/core';
import {
HttpClient,
HttpHeaders
} from '#angular/common/http';
import {
Jsonp
} from '#angular/http';
import {
Observable
} from 'rxjs';
import {
map
} from 'rxjs/operators';
import {
ConstantsService
} from './../../../services/constants.service';
#Injectable({
providedIn: 'root'
})
export class ProApiService {
apiRoot = this.root.APIroot;
diagnosisPROData: any;
drugData: any;
ProApiData: any;
drugApiData: any;
constructor(
private jsonp: Jsonp,
private http: HttpClient,
private root: ConstantsService) {}
why_diagnosisApi(url: any): Observable < any > {
let whyUrl = `${this.apiRoot}Mob_isabelPRO.php?
why_url=${url}&callback=JSONP_CALLBACK`;
return this.jsonp.request(whyUrl, 'callback')
.pipe(
map(
res => {
let why_diagnosis = res;
return why_diagnosis;
}
)
);
}
}
above code is from my service file.
this is the value i am getting in PC
this is the return on mobile
i dont know whats wrong with it. please suggest me the solution
Thanks

Ionic 4 swipeable tabs give error when swiping

In my angular app want to make tabs swipable .I am using directive and module in directive i am defined onTabInitialized method and calling in tabs.page.ts but it not working it gives error-> ERROR TypeError: Cannot read property 'onTabInitialized' of undefined. How to solve this problem plese help me..
swipe-tab.directive.ts
import { Directive, ElementRef, Output, EventEmitter, OnInit, Renderer2, OnDestroy } from '#angular/core';
import 'hammerjs';
#Directive({
selector: '[appSwipeTab]'
})
export class SwipeTabDirective implements OnInit, OnDestroy {
#Output() tabChange = new EventEmitter();
private currentTabIndex = 0;
private tabCount = 0;
private swipeCoords: [number, number];
private swipeDuration: number;
private browserSwipeGesture: HammerManager;
private touchListenersFns = [];
tabNames: String[] = [];
constructor(
public _el: ElementRef,
private _renderer: Renderer2
) {
console.log('[SwipeTabDirective] constructor');
}
ngOnInit() {
const tabsList = this._el.nativeElement.querySelectorAll('ion-tab-button');
for (let i = 0, len = tabsList.length; i < len; i += 1) {
this.tabNames.push(tabsList[i].tab);
}
this.tabCount = this.tabNames.length - 1;
console.log('[SwipeTabDirective] ngOnInit, tabNames: ', this.tabNames);
}
onTabInitialized(tabName: string): void {
console.log('[SwipeTabDirective] onTabInitialized, tabName: ', tabName);
this.currentTabIndex = this.tabNames.indexOf(tabName);
const currentTabName = `app-${tabName}`;
const elem = this._el.nativeElement.querySelectorAll(currentTabName)[0];
if (!elem) {
throw new Error('Make sure tab selector has app prefix');
} else {
const content = elem.getElementsByTagName('ion-content')[0];
if (content.querySelector('.swipe-area') === null) {
console.log('[SwipeTabDirective] adding swipe area');
this.createWrapperDiv(content);
}
}
}
createWrapperDiv(content: HTMLElement): void {
const divElement = this._renderer.createElement('div');
this._renderer.addClass(divElement, 'swipe-area');
this._renderer.insertBefore(content, divElement, null);
while (content.children.length > 1) {
const child = content.children[0];
this._renderer.removeChild(content, child);
this._renderer.appendChild(divElement, child);
}
this.addEventListeners(divElement);
}
addEventListeners(divElement: HTMLElement) {
if ('ontouchstart' in document.documentElement) {
this.touchListenersFns.push(
this._renderer.listen(divElement, 'touchstart', ($event) => {
this.deviceSwipeHandler($event, 'start');
}),
this._renderer.listen(divElement, 'touchend', ($event) => {
this.deviceSwipeHandler($event, 'end');
})
);
} else {
this.browserSwipeGesture = new Hammer(divElement);
this.browserSwipeGesture.on('swipe', (event) => {
this.browserSwipeHandler(event);
});
}
}
deviceSwipeHandler(event: TouchEvent, status: string): void {
console.log('[SwipeTabDirective] deviceSwipeHandler, status: ', status);
const coords: [number, number] = [event.changedTouches[0].pageX, event.changedTouches[0].pageY];
const time = new Date().getTime();
if (status === 'start') {
this.swipeCoords = coords;
this.swipeDuration = time;
} else if (status === 'end') {
const direction = [coords[0] - this.swipeCoords[0], coords[1] - this.swipeCoords[1]];
const duration = time - this.swipeDuration;
if (duration < 1000 && Math.abs(direction[0]) > 50
&& Math.abs(direction[0]) > Math.abs(direction[1] * 3)) {
if (direction[0] > 0) {
this.moveBackward();
} else {
this.moveForward();
}
}
}
}
browserSwipeHandler(event) {
console.log('[SwipeTabDirective] browserSwipeHandler, direction: ', event.direction);
switch (event.direction) {
case 2:
this.moveForward();
break;
case 4:
this.moveBackward();
break;
default:
break;
}
}
moveForward(): void {
console.log('[SwipeTabDirective] moveForward');
if (this.currentTabIndex < this.tabCount) {
this.currentTabIndex++;
this.tabChange.emit(this.tabNames[this.currentTabIndex]);
}
}
moveBackward(): void {
console.log('[SwipeTabDirective] moveBackward');
if (this.currentTabIndex > 0) {
this.currentTabIndex--;
this.tabChange.emit(this.tabNames[this.currentTabIndex]);
}
}
ngOnDestroy() {
if (this.touchListenersFns.length > 0) {
this.touchListenersFns.forEach(fn => fn());
} else if (this.browserSwipeGesture) {
this.browserSwipeGesture.off('swipe');
}
}
}
also make a module for export the directives which code show in below..
directives.module.ts
import { NgModule } from '#angular/core';
import { CommonModule } from '#angular/common';
import { SwipeTabDirective } from './swipe-tab.directive';
#NgModule({
declarations: [SwipeTabDirective],
imports: [
CommonModule
],
exports: [
SwipeTabDirective
]
})
export class DirectivesModule { }
The directive function use in tabs.page.ts and import directives module in tabs.page.ts
tabs.page.ts
import { Component, ViewChild } from '#angular/core';
import { IonTabs } from '#ionic/angular';
import { SwipeTabDirective } from '../directives/swipe-tab.directive';
#Component({
selector: 'app-tabs',
templateUrl: 'tabs.page.html',
styleUrls: ['tabs.page.scss']
})
export class TabsPage {
#ViewChild(SwipeTabDirective) swipeTabDirective: SwipeTabDirective;
#ViewChild('myTabs') tabRef: IonTabs;
constructor() { }
ionTabsDidChange($event) {
console.log('[TabsPage] ionTabsDidChange, $event: ', $event);
this.swipeTabDirective.onTabInitialized($event.tab);
}
onTabChange($event) {
console.log('[TabsPage] onTabChange, $event: ', $event);
this.tabRef.select($event);
}
}
In tabs.page.html i am define two function ionTabsDidChange and onTabChange ...
tabs.page.html
<ion-tabs appSwipetab (ionTabsDidChange)="ionTabsDidChange($event)" (tabChange)="onTabChange($event)" #myTabs>
<ion-tab-bar slot="bottom">
<ion-tab-button tab="tab1">
<ion-icon name="flash"></ion-icon>
<ion-label>Tab One</ion-label>
</ion-tab-button>
<ion-tab-button tab="tab2">
<ion-icon name="apps"></ion-icon>
<ion-label>Tab Two</ion-label>
</ion-tab-button>
<ion-tab-button tab="tab3">
<ion-icon name="send"></ion-icon>
<ion-label>Tab Three</ion-label>
</ion-tab-button>
</ion-tab-bar>
</ion-tabs>
I did some change in swipe-tab.directive.ts
from
const currentTabName = `app-${tabName}`;
to
const currentTabName = `${tabName}`;
and the error has gone.

Ionic 4 Hide Toolbar on scroll

I'm trying to implement a directive to hide the Toolbar while scrolling.
I tried using this tutorial:
https://medium.com/#gregor.srdic/ionic3-hidding-header-on-footer-on-content-scroll-15ab95b05dc5
This worked with Ionic 3, but doesn't work with Ionic 4.
On the following code I get the error:
private adjustElementOnScroll(ev) {
if (ev) {
console.log(ev);
ev.domWrite(() => {
let scrollTop: number = ev.scrollTop > 0 ? ev.scrollTop : 0;
let scrolldiff: number = scrollTop - this.lastScrollPosition;
this.lastScrollPosition = scrollTop;
let newValue = this.lastValue + scrolldiff;
newValue = Math.max(0, Math.min(newValue, this.config.maxValue));
this.renderer.setStyle(this.element.nativeElement, this.config.cssProperty, `-${newValue}px`);
this.lastValue = newValue;
});
}
}
Error:
ev.domWrite is not a function
I checked, and ev in Ionic 4 is a CustomEvent, not a ScrollEvent.
Any suggestions?
Above solutions no longer works. Ionic 4 beta APIs has changed a lot in recent months.
you have to import IonContent instead of Content.
//scroll-hide.directive.ts
import { IonContent, DomController } from '#ionic/angular';
import { Directive, ElementRef, Input, Renderer2, SimpleChanges } from '#angular/core';
import the directive where you want to use it, instead of app.module.ts
for example in relevant module,
//ex: home.module.ts
import { ScrollHideDirective } from '../../directives/scroll-hide.directive';
#NgModule({
...
declarations: [...,ScrollHideDirective],
...
})
then in the ts file,
//ex: home.page.ts
import { ScrollHideConfig } from '../../directives/scroll-hide.directive';
export class HomePage implements OnInit {
...
footerScrollConfig: ScrollHideConfig = { cssProperty: 'margin-bottom', maxValue: undefined };
headerScrollConfig: ScrollHideConfig = { cssProperty: 'margin-top', maxValue: 54 };
...
}
reversed version of directive
//ex: scroll-hide.directive.ts
import { IonContent, DomController } from '#ionic/angular';
import { Directive, ElementRef, Input, Renderer2, SimpleChanges } from '#angular/core';
#Directive({
selector: '[scrollHide]'
})
export class ScrollHideDirective {
#Input('scrollHide') config: ScrollHideConfig;
#Input('scrollContent') scrollContent: IonContent;
contentHeight: number;
scrollHeight: number;
lastScrollPosition: number;
lastValue: number = 0;
constructor(private element: ElementRef, private renderer: Renderer2, private domCtrl: DomController) {
}
ngOnChanges(changes: SimpleChanges) {
if(this.scrollContent && this.config) {
this.scrollContent.scrollEvents = true;
let scrollStartFunc = async (ev) => {
const el = await this.scrollContent.getScrollElement();
this.contentHeight = el.offsetHeight;
this.scrollHeight = el.scrollHeight;
if (this.config.maxValue === undefined) {
this.config.maxValue = this.element.nativeElement.offsetHeight;
}
this.lastScrollPosition = el.scrollTop;
};
if(this.scrollContent && this.scrollContent instanceof IonContent) {
this.scrollContent.ionScrollStart.subscribe(scrollStartFunc);
this.scrollContent.ionScroll.subscribe(async (ev) => this.adjustElementOnScroll(ev));
this.scrollContent.ionScrollEnd.subscribe(async (ev) => this.adjustElementOnScroll(ev));
} else if(this.scrollContent instanceof HTMLElement) {
(this.scrollContent as HTMLElement).addEventListener('ionScrollStart', scrollStartFunc);
(this.scrollContent as HTMLElement).addEventListener('ionScroll',async (ev) => this.adjustElementOnScroll(ev));
(this.scrollContent as HTMLElement).addEventListener('ionScrollEnd',async (ev) => this.adjustElementOnScroll(ev));
}
}
}
private adjustElementOnScroll(ev) {
if (ev) {
this.domCtrl.write(async () => {
const el = await this.scrollContent.getScrollElement();
let scrollTop: number = el.scrollTop > 0 ? el.scrollTop : 0;
let scrolldiff: number = scrollTop - this.lastScrollPosition;
this.lastScrollPosition = scrollTop;
let newValue = this.lastValue + scrolldiff;
newValue = Math.max(0, Math.min(newValue, this.config.maxValue));
this.renderer.setStyle(this.element.nativeElement, this.config.cssProperty, `-${newValue}px`);
this.lastValue = newValue;
});
}
}
}
export interface ScrollHideConfig {
cssProperty: string;
maxValue: number;
}
the html ex: page.html (No Change)
<ion-header [scrollHide]="headerScrollConfig" [scrollContent]="pageContent">
...
</ion-header>
<ion-content #pageContent fullscreen>
...
</ion-content>
<ion-footer [scrollHide]="footerScrollConfig" [scrollContent]="pageContent">
...
</ion-footer>
hope it helps.
Modified directive for Ionic 4.
import { Content, DomController } from '#ionic/angular';
import { Directive, ElementRef, Input, Renderer2, SimpleChanges } from '#angular/core';
#Directive({
selector: '[scrollHide]'
})
export class ScrollHideDirective {
#Input('scrollHide') config: ScrollHideConfig;
#Input('scrollContent') scrollContent: Content;
contentHeight: number;
scrollHeight: number;
lastScrollPosition: number;
lastValue: number = 0;
constructor(private element: ElementRef, private renderer: Renderer2, private domCtrl: DomController) {
}
ngOnChanges(changes: SimpleChanges) {
if (this.scrollContent && this.config) {
this.scrollContent.ionScrollStart.subscribe(async (ev) => {
const el = await this.scrollContent.getScrollElement();
this.contentHeight = el.offsetHeight;
this.scrollHeight = el.scrollHeight;
if (this.config.maxValue === undefined) {
this.config.maxValue = this.element.nativeElement.offsetHeight;
}
this.lastScrollPosition = el.scrollTop;
});
this.scrollContent.ionScroll.subscribe((ev) => this.adjustElementOnScroll(ev));
this.scrollContent.ionScrollEnd.subscribe((ev) => this.adjustElementOnScroll(ev));
}
}
private adjustElementOnScroll(ev) {
if (ev) {
this.domCtrl.write(async () => {
const el = await this.scrollContent.getScrollElement();
let scrollTop: number = el.scrollTop > 0 ? el.scrollTop : 0;
let scrolldiff: number = scrollTop - this.lastScrollPosition;
this.lastScrollPosition = scrollTop;
let newValue = this.lastValue + scrolldiff;
newValue = Math.max(0, Math.min(newValue, this.config.maxValue));
this.renderer.setStyle(this.element.nativeElement, this.config.cssProperty, `-${newValue}px`);
this.lastValue = newValue;
});
}
}
}
export interface ScrollHideConfig {
cssProperty: string;
maxValue: number;
}
The event may have changed in Ionic 4, but you can still import the DomController from #ionic/angular
import {..., DomController } from "#ionic/angular";
and inject it in the constructor
constructor(
// ...
private domCtrl: DomController
) { }
And then use the write() method like this:
private adjustElementOnScroll(ev) {
if (ev) {
this.domCtrl.write(() => {
// ...
});
}
}
The DomController is just a way for Ionic to create a queue for callbacks that would write or read the DOM in order to use the window.requestAnimationFrame() method behind the scenes.
For more information, please visit:
DomController source code
requestAnimationFrame MDN
The below code worked for me, with minor corrections from above code
import { Content, DomController } from '#ionic/angular';
import { Directive, ElementRef, Input, Renderer2, SimpleChanges } from '#angular/core';
#Directive({
selector: '[scrollHide]'
})
export class ScrollHideDirective {
#Input('scrollHide') config: ScrollHideConfig;
#Input('scrollContent') scrollContent: Content;
contentHeight: number;
scrollHeight: number;
lastScrollPosition: number;
lastValue: number = 0;
constructor(private element: ElementRef, private renderer: Renderer2, private domCtrl: DomController) {
}
ngOnChanges(changes: SimpleChanges) {
if(this.scrollContent && this.config) {
this.scrollContent.scrollEvents = true;
let scrollStartFunc = async (ev) => {
const el = await this.scrollContent.getScrollElement();
this.contentHeight = el.offsetHeight;
this.scrollHeight = el.scrollHeight;
if (this.config.maxValue === undefined) {
this.config.maxValue = this.element.nativeElement.offsetHeight;
}
this.lastScrollPosition = el.scrollTop;
};
if(this.scrollContent && this.scrollContent instanceof Content) {
this.scrollContent.ionScrollStart.subscribe(scrollStartFunc);
this.scrollContent.ionScroll.subscribe(async (ev) => this.adjustElementOnScroll(ev));
this.scrollContent.ionScrollEnd.subscribe(async (ev) => this.adjustElementOnScroll(ev));
} else if(this.scrollContent instanceof HTMLElement) {
(this.scrollContent as HTMLElement).addEventListener('ionScrollStart', scrollStartFunc);
(this.scrollContent as HTMLElement).addEventListener('ionScroll',async (ev) => this.adjustElementOnScroll(ev));
(this.scrollContent as HTMLElement).addEventListener('ionScrollEnd',async (ev) => this.adjustElementOnScroll(ev));
}
}
}
private adjustElementOnScroll(ev) {
if (ev) {
this.domCtrl.write(async () => {
const el = await this.scrollContent.getScrollElement();
let scrollTop: number = el.scrollTop > 0 ? el.scrollTop : 0;
let scrolldiff: number = scrollTop - this.lastScrollPosition;
this.lastScrollPosition = scrollTop;
let newValue = this.lastValue + scrolldiff;
newValue = Math.max(0, Math.min(newValue, this.config.maxValue));
this.renderer.setStyle(this.element.nativeElement, this.config.cssProperty, `-${newValue}px`);
this.lastValue = newValue;
});
}
}
}
export interface ScrollHideConfig {
cssProperty: string;
maxValue: number;
}

Events in Ionic v4

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'];
}
}

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
}
}