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

The 'formGroup' property cannot be bound as it is not recognized as a valid property of 'form' in Angular 7

I tried implementing a login feature using web API with Angular 7, but encountered an error when using <form [formGroup]="loginForm" (submit)="loginFormSubmit()">. What could be causing this issue? login.component.html <form [formGroup]="loginFo ...

Attempting to develop a server component that will transmit a JSON result set from a MySQL database located on the local server. What is the best method to send the server object (RowDataPacket) to the

After successfully rendering server-side pages and creating forms with react hooks for database updates, I encountered a challenge in integrating Ag-Grid into my application. Despite being able to retrieve data from the database using the mysql2 module and ...

An issue occurred while attempting to retrieve information from the database table

'// Encounter: Unable to retrieve data from the table. // My Code const sql = require('mssql/msnodesqlv8'); const poolPromise = new sql.ConnectionPool({ driver: 'msnodesqlv8', server: "test.database.windows.net", ...

There is no 'next' property available

export function handleFiles(){ let files = retrieveFiles(); files.next(); } export function* retrieveFiles(){ for(var i=0;i<10;i++){ yield i; } } while experimenting with generators in T ...

The Angular2 component link imported in the core.module is not functioning properly

Adhering to the guidelines provided in the Angular style guide found at https://angular.io/styleguide#!#04-11, I have created a simple navigation setup. My app.component contains links like <a routerLink="hello">hello</a>, which work perfectly ...

Issue: The parameter "data" is not recognized as a valid Document. The input does not match the requirements of a typical JavaScript object

I encountered the following issue: Error: Argument "data" is not a valid Document. Input is not a plain JavaScript object. while attempting to update a document using firebase admin SDK. Below is the TypeScript snippet: var myDoc = new MyDoc(); myDo ...

Toggle Submenu Visibility with a Click

One section of my code is located in sidebar.component.html : <ul class="nav"> <li routerLinkActive="active" *ngFor="let menuItem of menuItems" class="{{menuItem.class}} nav-item"> &l ...

Struggling to dynamically create form controls within Angular forms and receiving the following error in the console: "TypeError: feature_r5.get is not a function"

When I click a button in my Angular v14 HTML template, I am trying to dynamically generate form controls and although I am able to generate them, an error is popping up in the console. ERROR TypeError: feature_r5.get is not a function at PostAdvComponent_ ...

Employing [style.something.px]="2" in Angular to specify the thickness of the border

Presently, I am setting the width of the element using this code format: <div [style.width.px]="size" [style.height.px]="size"></div> What I am aiming for is to utilize a comparable format but to define the border-width css attribute, such as ...

What is the best way to fake the retrieval of '$location' using mock for angular.element(document).injector() in jasmine 3.6?

Currently, I am encountering an issue. I am unsure of how to mock the following method: private angularLocation = angular.element(document).injector().get('$location'); In my hybrid angular application, this method is crucial for navigating betw ...

What are the steps to enable full functionality of the strict option in TypeScript?

Despite enforcing strict options, TypeScript is not flagging the absence of defined types for port, req, and res in this code snippet. I am using Vscode and wondering how to fully enforce type checking. import express from 'express'; const app ...

I am encountering an "ERROR null" message in my Angular application within VSCode. How can I identify the root cause of this issue?

https://i.sstatic.net/bIZcK.png After compiling my Angular v17 project, I encountered error messages in the terminal that do not provide any specific reference or link to the issue. Surprisingly, the web browser console does not display any errors either. ...

Angular 8 date validation for start date and end date on a mat-date-picker

My current task involves working with the Mat date picker, specifically focusing on setting up validation rules for start and end dates. One important rule to note is that the end date should always be after or equal to the start date. For instance: If th ...

Guide on incorporating text input areas into specific positions within a string

Looking for a way to replace specific words in a string with input fields to enter actual values? For example... Dear Mr. [Father_name], your son/daughter [name] did not attend class today. This is what I want it to look like... Dear Mr. Shankar, your ...

Ways to limit file access and downloads on an IIS server

After deploying our Angular app (dist folder) on an IIS server, everything seems to be working well. However, there is a concerning issue where anyone can access and download the font files directly from the server without needing to log in. For example, o ...

Internal Server Error in Angular 2+ and Laravel Integration

Facing an issue with a post request from Angular to Laravel where I am encountering an Internal Server Error, although it works perfectly fine in Postman. api.php <?php use Illuminate\Http\Request; Route::post('/addHouse&ap ...

Designate as a customizable class property

I'm struggling to create a versatile inheritance class for my services. Currently, I have two service classes named Service_A and Service_B that essentially do the same thing. However, Service_A works with Class_A while Service_B works with Class_B. T ...

Material-UI and TypeScript are having trouble finding a compatible overload for this function call

Currently, I'm in the process of converting a JavaScript component that utilizes Material-ui to TypeScript, and I've encountered an issue. Specifically, when rendering a tile-like image where the component prop was overridden along with an additi ...

Utilize Sequelize's cascade feature within your application

I'm currently building a web application using sequelize and typescript. In my database, I have three tables: WfProjectObject, which is connected to WfProject, and WfStep, also linked to WfProject. My goal is to include WfStep when querying WfProject ...

The browser failed to load the Angular controller

Within our latest project, we successfully implemented microservices with spring boot. The web application has been deployed on a Unix box. However, we are encountering an unusual problem. Although the necessary JS files are contained within the JAR file ...