how to navigate to a different page programmatically upon selecting an option in the side menu

ionic start mySideMenu sidemenu --v2

After creating a sidemenu using the code above, I implemented some login-logout functionality by storing user details in a localStorage variable named "userDetails". When clicking on the logout option from the sidemenu, it redirects to the login page.

import { homePage } from '../pages/home/home';

import { DetailsPage } from '../pages/Details/Details';

import { AddclientPage } from '../pages/Addclient/Addclient';
import { Storage } from '@ionic/storage';
import { LoginPage } from '../pages/login/login';


@Component({
  templateUrl: 'app.html'
})
export class MyApp {
 @ViewChild(Nav) nav: Nav;
  rootPage: any =  homePage;
  
  pages: Array<{title: string, component: any,icon:string}>;
  
  constructor(platform: Platform,public storage:Storage,public mqttservice:Mqttservice) {
  
    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();
    });
     this.pages = [
      { title: 'Home ', component: homePage ,icon:"home"},
           
      { title:'Addclient',component:AddclientPage,icon:'add'},
     
      {title: 'Users' ,component:DetailsPage,icon:"people"},
      { title:'addclient',component:AddclientPage,icon:"person-add"},
      {title:'Logout',component:LoginPage,icon:"log-out"}
      
    ];
  }

 
 

}

However, I want to remove the localStorage variable and then redirect to the login page when the user clicks on logout. So, I created a method that removes the "userDetails" variable and redirects to the "loginpage", but I am encountering an error stating that "can not read property 'setRoot' of undefined".

import { homePage } from '../pages/home/home';

import { DetailsPage } from '../pages/Details/Details';

import { AddclientPage } from '../pages/Addclient/Addclient';
import { Storage } from '@ionic/storage';
import { LoginPage } from '../pages/login/login';


@Component({
  templateUrl: 'app.html'
})
export class MyApp {
 @ViewChild(Nav) nav: Nav;
  rootPage: any =  homePage;
  
  pages: Array<{title: string, component: any,icon:string}>;
  
  constructor(platform: Platform,public storage:Storage,public mqttservice:Mqttservice) {
  
    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();
    });
     this.pages = [
      { title: 'Home ', component: homePage ,icon:"home"},
           
      { title:'Addclient',component:AddclientPage,icon:'add'},
     
      {title: 'Users' ,component:DetailsPage,icon:"people"},
      { title:'addclient',component:AddclientPage,icon:"person-add"},
      {title:'Logout',component:this.logout(),icon:"log-out"}
      
    ];
  }
  logout(){
  this.storage.remove('userDetails);
  this.nav.setRoot(LoginPage);
  }
 
  

}

Answer №1

When setting up the pages property, make sure not to call the logout method. Here's how it should look:

   this.pages = [
      { title: 'Home ', component: homePage, icon:"home" },   
      { title:'Addclient', component:AddclientPage, icon:'add' },
      { title: 'Users', component:DetailsPage, icon:"people" },
      { title:'addclient', component:AddclientPage, icon:"person-add" },
      { title:'Logout', component:null, icon:"log-out" }
    ];

Instead of having the logout method under component for the Logout option, set it as null. Then, in your openPage method:

  openPage(page) {

    if(!page.component) {
      // Only the logout has the component as null
      this.logout();
    } else {
      // Reset the content nav to have just this page
      // we wouldn't want the back button to show in this scenario
      this.nav.setRoot(page.component);
    }
  }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

npm - Configuring the maximum memory usage in npm

I encountered an error message while trying to build my Angular project, The error states: "CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out of memory" I read somewhere that adjusting the max-old-space-size in npm could resolve this issue. How ...

Ionic Beta 10 iOS Build - You are attempting to create an iOS build without having the platform installed

After smoothly developing for Android on a Windows computer, I recently switched to a Mac Mini. Once I updated the OS to El Capitan, installed XCode, and set up everything else (NodeJS, Ionic, etc.), I attempted to build for iOS only to encounter the follo ...

"Utilizing Angular's dynamic variable feature to apply ngClass dynamically

Looking for guidance on Angular - color change on button click. The loop binding is functioning well with dynamic variable display in an outer element like {{'profile3.q2_' + (i+1) | translate}}, but facing issues with [ngClass] variable binding ...

Exploring the Material Drawer functionality within an Angular application

I'm having trouble integrating the Material Drawer component into my Angular app. Despite following the instructions on https://material.io/develop/web/components/drawers/, it's not rendering properly. Could someone please provide a detailed, s ...

The HTML canvas drawImage method overlays images when the source is modified

Trying to implement a scroll animation on my website, I came across a guide for creating an "Apple-like animation" using image sequences. Even though I'm new to Angular, I attempted to adapt the code to work with Angular. However, instead of animatin ...

What is the best way to verify the input of a TextField element?

When I visited the Material UI Components documentation for TextField, I was hoping to find an example of validation in action. Unfortunately, all they showed was the appearance of the invalid TextField without any insight into the actual validation code i ...

What steps are involved in setting up a SAML service provider using @node-saml/node-saml?

I'm currently working on a SAML SP implementation using the @node-saml/node-saml library. Despite creating the necessary source code, I am facing an issue with the SAML authentication not functioning as expected. Can anyone provide guidance on how to ...

Having trouble retrieving the date value from a datepicker in Angular ngForm

I am struggling to fetch a value from the mat-datepicker in my Angular project. Whenever I try, it returns as undefined. I have implemented ngForm and ngModel, but I seem to have made a mistake somewhere. <form #f="ngForm" (ngSubmit)="registerClient(f. ...

Error encountered: No matching overload found for MUI styled TypeScript

I am encountering an issue: No overload matches this call. Looking for a solution to fix this problem. I am attempting to design a customized button. While I have successfully created the button, I am facing the aforementioned error. Below is my code ...

Defining the range of an array of numbers in TypeScript: A complete guide

When working with Next.js, I created a function component where I utilized the useState hook to declare a variable for storing an array of digits. Here is an example: const [digits, setDigits] = useState<number[]>(); I desire to define the range of ...

What is the best way to manage optional peer dependency types while releasing a TypeScript package?

I'm trying to figure out the best way to handle optional peer dependencies when publishing a TypeScript package on npm. My package provides a function that can accept input from either one of two peer dependencies. How should I define these optional p ...

Unable to provide any input while utilizing npm prompts

After installing npm prompts, I encountered a strange issue. When trying to run the example code for npm prompts, I found that I couldn't enter any input at all. The underscore in the input field would blink for a few seconds, then the cursor would ju ...

It appears that the library (@ngx-translate/core) that contains TranslateModule may not be compatible with Angular Ivy, resulting in an error in the Angular application

Encountering an issue after upgrading my Angular app from version 15 to 16 and running npm start. The error message is related to compatibility with Angular Ivy, specifically mentioning @ngx-translate/core. Looking for a newer version of the library or adv ...

Encountering 404 errors when reloading routes on an Angular Azure static web app

After deploying my Angular app on Azure static web app, I encountered an error. Whenever I try to redirect to certain routes, it returns a 404 error. However, if I navigate from one route to another within the app, everything works fine. I have attempted t ...

Obtaining the response header in Angular 7 using flatMap

I am attempting to access the response header inside flatMap this.http.post<HttpResponse<any>>(`${environment.URL_API}/patients/v1/`, patient, {observe: 'response'}).pipe( flatMap((res: any) => { console.log(res) var loca ...

Are fp-ts and Jest the perfect pairing for testing Option and Either types with ease?

When working with fp-ts, and conducting unit tests using Jest, I often come across scenarios where I need to test nullable results, typically represented by Option or Either (usually in array find operations). What is the most efficient way to ensure that ...

Issues with binding Angular reactive forms

Exploring the construction of nested reactive forms: https://stackblitz.com/edit/angular-mgrfbj The project structure is as follows: ---create company form (hello.component.ts) --- company details form (company-details.component.ts) --- [ ...

The @Input directive is not compatible with the OnPush change detection strategy

page.html <app-parcel-delivery-cost-promo [parcelDeliveryCost]="parcelDeliveryCost"> </app-parcel-delivery-cost-promo> page.ts changeDetection: ChangeDetectionStrategy.OnPush, parcelDeliveryCost: Partial<ParcelDeliveryCostModel>; ...

What is the process in Typescript for importing JSON files and dynamically searching for values based on keys?

When working with typescript 3.0.3, I encountered an issue while importing a json file in the following manner: import postalCodes from '../PostalCodes.json'; The json file has the structure shown below: { "555": { "code": 555, "city": "Sc ...

Typescript Server Problem: Critical Error - Mark-compacts Inefficiently Close to Heap Limit, Allocation Unsuccessful - JavaScript Heap Exhausted

Whenever I run my CRA project, I consistently encounter this error in my console. It seems to be related to the typescript server. Is there a solution for this issue? 99% done plugins webpack-hot-middlewarewebpack built preview 7c330f0bfd3e44c3a97b in 64 ...