I am verifying the user's login status and directing them to the login page if they are not already logged in

My goal is to utilize ionViewWillEnter in order to verify if the user is logged in. If the check returns false, I want to direct them to the login page and then proceed with the initializeapp function. My experience with Angular and Ionic is still limited, so any advice or suggestions would be greatly appreciated.

ionViewCanEnter() {
    console.log("1");
    console.log(this.userSevice.isUserLoggedIn());
    if (this.userSevice.isUserLoggedIn() === false){
      this.nav.push(LoginPage);
      alert("user is logging in");
    }
    else{
      this.initializeApp();
    }
  }

Answer №1

Angular has a fantastic feature known as Guard, which can be utilized to manage the login flow within an angular application.

You have the ability to create an auth guard and incorporate it into your router or any other relevant location to direct users to the login page if they are not logged in and attempting to access restricted areas of the website.

This is an example of a basic auth guard:

@Injectable()
export class AuthGuard implements CanActivate {

  constructor(private router: Router, private authService: AuthService) { }

  canActivate(): Observable<boolean> | boolean {
    // Check if this is the initial call. If not, return a 
    // simple boolean value based on the user object from the authService.
    // Otherwise:

    return this.authService.getAuthenticated.map(user => {
          this.authService.setUser(user);
          return user ? true : false;
    })

  } 
}

Incorporate the guard in your router setup like this:

const routes: Routes = [
  {
    path: '',
    canActivate: [AuthGuardService],
    runGuardsAndResolvers: 'always',
  }
   ...
]

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

Creating a variable within an ngFor loop

For my angular2 project, I need to display a matrix of workers and courses. Here's the current code I am using: <tr *ngFor="let worker of workers"> <td class="{{worker.fired ? 'fired-worker':''}}">{{worker.lastName ...

The express application's GET route is causing a "Cannot GET" error to be thrown

I am managing different types of pages: the main root page (/) today's chapter page (/929 OR /929/) which eventually redirects to /929/<CHAPTER> where <CHAPTER> is a natural number between 1 to 929 individual chapter pages (/929/<CHAP ...

Angular 16 facing compatibility problems with Apollo-angular and React dependencies

I have integrated apollo-client into my Angular 16 project. "@apollo/client": "^3.8.7", "apollo-angular": "^5.0.2", "graphql": "^16.8.1", This snippet shows how the providers array is ...

I'm curious if anyone has experimented with implementing TypeScript enums within AngularJS HTML pages

During my Typescript project, I defined an enum like this: enum Action { None = 0, Registering = 1, Authenticating = 2 }; In the controller, I declared a property named action as follows: class AuthService implements IAuthService { action: number; ...

Ensuring that the field is empty is acceptable as long as the validators are configured to enforce

I have successfully created a form using control forms. idAnnuaire: new FormControl('',[Validators.minLength(6),Validators.maxLength(6)]), However, I am facing an issue where when the field is left empty, {{form.controls.idAnnuaire.valid }} is ...

Fetching all data from a SQLite database in a Listview using React Native

I have been utilizing the library found at https://github.com/andpor/react-native-sqlite-storage in my react native project. To retrieve a single row from the database, I use the following code: db.transaction((tx) => { tx.executeSql('SEL ...

The Next.js 13 function getQueriesData does not have any matching overloads for TypeError

Having a TypeScript error issue while using the getQueriesData function in Next.js 13 with React Query. Below is my code snippet: // app/products.tsx import { getQueryClient } from "@/app/providers/getQueryClient"; import { useQuery, useQueryCli ...

Angular causing issues with Perfect Scrollbar functionality

In an attempt to enhance the scrollbar in my Angular application, I integrated the following library: https://github.com/zefoy/ngx-perfect-scrollbar Following the guidelines provided in the documentation from the link, I included imports into my app.modul ...

refresh specific route when navigating to the same URL

Can the onSameUrlNavigation: reload be applied to just a single route in Angular? ...

Guide to Display chat.html Overlay on home.html Using Ionic 2

In my Ionic project, I have two pages: home.html chat.html I am looking to display chat.html over home.html at the bottom right as a chat window. How can I accomplish this? I have attempted to illustrate what I envision in an image: ...

Verify if the property in every element of the array is not empty

How can you determine if all employees have a non-null value for the SSN property in the given object? Employees: { id: 0, name: "John", SSN: "1234" } { id: 1, name: "Mark", SSN: "1876" } { id: 2, name: "Sue&q ...

What are some strategies for enhancing TypeScript/Node speed in VSCode with the help of WSL2 and Docker?

My development environment consists of VSCode running on Windows (v1.58.2) with the Remote WSL extension (v0.58.2). I have Docker Desktop (3.5.2, engine: 20.10.7) set up to work with Linux containers through the WSL2 backend. Within these containers, I a ...

Angular does not display results when using InnerHtml

I'm currently in the process of creating a weather application with Angular, where I need to display different icons based on the weather data received. To achieve this functionality, I have developed a function that determines the appropriate icon to ...

"Encountering a Vue error while attempting to register the Can component globally with CASL +

I have successfully created a vue + typescript application using vue-cli. I followed the instructions from https://stalniy.github.io/casl/v4/en/package/casl-vue and added the following code: // main.ts import Vue from 'vue'; import App from &apo ...

The module X is experiencing a metadata version mismatch error. Version 4 was found instead of the expected version 3 while resolving symbol Y

I am in the process of creating an Angular 4 application using angular-cli (ng build) and incorporating ngx-clipboard. Recently, I have encountered a sudden error that has persisted for a few days despite there being no changes to my source code: ERROR in ...

invoke a specified function at runtime

I recently came across a useful library called https://github.com/ivanhofer/typesafe-i18n This library has the capability to generate strongly typed translation data and functions, as illustrated below. (the examples provided are simplified for clarity) e ...

Issue with assigning objects to an array

I'm currently working on a TypeScript application and I've run into an issue with assigning values. Here are the interfaces for reference: export interface SearchTexts { SearchText: SearchText[]; } export interface SearchText { Value: st ...

What steps should be followed in order to generate a child or item with no assigned key

Here is my TypeScript code designed to automatically record the time of data creation: import * as functions from 'firebase-functions'; export const onAccCreate = functions.database .ref('/Agent/{AgentID}') .onCreate((snapshot, contex ...

The error message "printer.node is not a valid Win32 application" indicates that the

I created a node API for my Angular application that utilizes the node-printer package to print PDF files generated by node. However, when I attempted to run my application using nodemon, an error occurred. Error message: "node printer.node is not a val ...

Intellisense in VSCode is failing to suggest subfolder exports

In my setup, I have a repository/module specifically designed to export TypeScript types into another project. Both of these projects are using TypeScript with ECMAScript modules. The relevant part of the tsconfig.json configuration is as follows: "ta ...