Navigating to a different page in Ionic 2 upon app initialization

Is there a way to automatically redirect the page to the home page instead of displaying the login page if there is already a token stored in localStorage? I currently have the following code in the constructor() of app.component.ts, but it still displays the login page first before the request is completed.

statusBar.backgroundColorByHexString('#D32F2F');
      splashScreen.hide();
      if(localStorage.getItem('token')){
        authProvider.silent_login().subscribe(res => {
          console.log(res);
          if(res.error==0){
            this.rootPage = HomePage;
          }
        })
      }

Answer №1

Do you enjoy this code snippet?

    @ViewChild(Nav) nav: Nav;
    rootPage: any = null; // Set to null initially
    pages: Array<{title: string, component: any}>;

    constructor(public platform: Platform, 
                public statusBar: StatusBar, 
                public splashScreen: SplashScreen,
                public commonProvider: CommonProvider) {

        this.commonProvider.retrieve("is_login").then(loggedIn => {
            // Determine the appropriate page based on login status
            this.rootPage = loggedIn ? TabsPage : SigninPage;
        });
     }

Answer №2

In order to address the issue, we can create a splash page as a credentials checker and designate it as the root page of the application. Within the constructor, we can verify the token - if it fails, we redirect to the login page; if successful, we set the root page to the homepage.

Utilizing a splash page for credential verification seems to be the most effective solution in this scenario.

This approach may prove beneficial for others facing similar challenges.

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

Using RXJS with Typescript to wait for an observable to emit until another observable of type boolean evaluates to false

In my current setup, when a user navigates in a view, an API call is made to fetch the data for that specific view. This data is then used later on to decide whether a dialog should pop up when a user performs an action. While the solution is functional a ...

Tips on maintaining the chosen product while navigating to a different component

I have a dilemma with 2 different components that are responsible for creating an invoice. The first component adds more products The second component adds invoice details Initially, I enter the invoice details and select the client's name. The sel ...

Contrasting between betting text and console error logging in Angular

Currently working on an Angular application and exploring the best practices for error logging. I'm pondering whether to opt for console logging or text-based logging. Text-based logging seems beneficial as it stores historical error data on the serv ...

Slow performance on Ionic page with input fields

My ionic app is experiencing slow performance on pages with inputs. For example, a select input with 4 items has a delay of approximately 800ms, and when dismissing the keyboard, a white blank block remains on screen for about 500ms. This app consists of ...

Navigating horizontally to find a particular element

I developed a unique Angular component resembling a tree structure. The design includes multiple branches and nodes in alternating colors, with the selected node marked by a blue dot. https://i.stack.imgur.com/fChWu.png Key features to note: The tree&ap ...

Can you explain the mechanics behind the functionalities of @angular and @type dependencies?

This inquiry may have been raised before, but I couldn't uncover all the solutions. If that's the case, my apologies. I have a good grasp on how package.json and dependencies / dev-dependencies function in Node applications. Currently delving i ...

Sending properties to MUI Box component enhancer (Typescript)

I'm having trouble figuring out how to pass props to override the Box component. I specifically need to pass position="end" as InputAdornment requires it, but I can't seem to find the proper way in the documentation. Here's the complete co ...

Elevating Angular version from 9 to 12

I am currently in the process of upgrading our Angular application from version 9 to 12. However, I have hit a roadblock as I am still stuck on step 1, which is upgrading from version 9 to 10. Running ng update @angular/core@10 @angular/cli@10 --allow-dir ...

What events can cause all store states to be loaded when the page is altered?

I am currently utilizing ngrx/store, ngrx/effects, and ngrx/router. The implementation of my effects is structured as follows: @Effect() loadOneProduct$ = this.updates$ .whenAction(LOAD_ONE_PRODUCT) .switchMap(() => this.productService.loadOn ...

Can a console application be created using AngularJS technology?

My task involves creating a console application that interacts with an API, modifies the data, and displays it on the console when a specific command is run. Is it feasible to achieve this using AngularJS? If not, what about utilizing Angular6 instead? To ...

Combining multiple data types in an AJV array

Imagine you have the following defined type: type MixedArray = Array<number | string>; Now, let's say you have some sample data that needs to be validated: [ 'dfdf', 9, 0, 'sdfdsf' ] How can you create an Ajv JSONSchemeType ...

The ApexCharts Radar Chart always pushes the data to its maximum potential, creating visually stunning charts that showcase

It appears that with apex charts, the radar chart always scales to the data you have specified. Is it possible for the radar chart to scale to the maximum value instead of just the maximum data value in the series? Based on kikon's response and his ...

Ways to Close a Modal in Ionic 5

I have a scenario where I need to open a modal, perform an asynchronous action, and then automatically dismiss the modal once the action is completed. Specifically, I want to use the fetchData function to handle the async task. @Component({ }) export cla ...

Looping inside a loop with Angular's ngFor

I am working on an Angular + Firebase app. Within one of my components, I am retrieving elements from the Firebase DB and binding them into a template using *ngFor: <div *ngFor="let comment of (comments | async)> <div>{{ comment.text }}< ...

What are the steps to extract information from an observable?

Having trouble retrieving data from a request? I've encountered an issue where the data retrieved inside .subscribe in an observable function is returning as undefined when trying to access it outside the function. It's quite frustrating! Here i ...

The Nuxt Vuex authentication store seems to be having trouble updating my getters

Despite the store containing the data, my getters are not updating reactively. Take a look at my code below: function initialAuthState (): AuthState { return { token: undefined, currentUser: undefined, refreshToken: undefined } } export c ...

Angular 2 - Issue: Parameters provided do not correspond to any signature of call target

I'm encountering the following error message: "error TS2346: Supplied parameters do not match any signature of call target." This occurs when attempting to reject a promise, but I believe the code adheres to the required signatures. Any suggestions on ...

Steps for inserting a script tag in an Angular component

My Angular/Typescript website needs to integrate a third-party script that generates a table. However, I'm facing issues with rendering the table within the home.component.html file. I've managed to embed the script, but it doesn't seem to ...

The LoaderRunner callback was triggered by the bootstrap version ^3.4.1 before

I encountered a surprising error while using the Azure Build pipeline, specifically in the loadrunner.js file. The error message from the pipeline is: "The callback was already called". C:\Windows\system32\cmd.exe /D /S /C ""C:&bso ...

Updating text inputs in Angular can be done more efficiently using Angular Update

I need to make adjustments to an Angular application so that it can run smoothly on older machines. Is there a more efficient method for updating a text input field without using (keyup) to update after each keystroke? I haven't been able to find any ...