Ensure to call the typescript file every time the page is reloaded or when a URL change occurs

Looking to integrate a session feature into my Angular 5 application. I aim to create a single TypeScript file that will handle user login validation. Is there a way to trigger this file every time the page reloads or the URL changes? Need guidance on implementation.

Answer №1

Utilize the AuthGuard concept.

Begin by creating a auth-guard.service.ts file.

import { Injectable } from '@angular/core';
import { CanActivate, CanActivateChild } from '@angular/router';

@Injectable()
export class AuthGuard implements CanActivate, CanActivateChild {

  canActivate() {
    console.log('Checking if user is logged in');
    return true;
  }

  canActivateChild() {
    console.log('Checking child route access');
    return true;
  }

}

Next, integrate this into your routing configuration:

export const appRoutes: Routes = [
  {
    path: 'dashboard',
    children: [
      {
        path: '',
        canActivate: [AuthGuard],
        component: DashboardComponent
      },
      {
        path: 'users',
        component: DashboardUsersComponent,
        canActivateChild: [AuthGuard],
        children: [
          {
            path: '',
            component: DashboardUsersHomeComponent
          },
          {
            path: ':username',
            component: DashboardUserDetailsComponent,
            canDeactivate: [CanDeactivateGuard]
          }
        ]
      }
    ]
  }
]; 

Check out these resources for more information:

Link 1

Link 2

Link 3

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

Put the item at the start of a viewable list

I have a critical Angular component that efficiently loads data into an Observable<Item[]> using a cleverly implemented BehaviorSubject<Item[]> triggered by the scroll position of a container reaching the bottom. The essential properties and t ...

Tips for clearing express-session during a logout process in a Node.js application

Currently, we utilize express-session to store data in our Node application. For instance, we set user information like this: req.session.userinfo = userObj; Could you advise on the best practice for clearing session information during logout? We apprecia ...

What prevents the creation of an Angular app without any content?

Why am I unable to create an empty Angular app? I have been following the guidelines provided on the official documentation: https://angular.io/guide/setup-local. To start off, I installed Angular using the command: npm install -g @angular/cli. Now, whe ...

Having difficulties injecting a Service into a TypeScript Controller

I recently started working with TypeScript and I created a controller where I need to inject a service in order to use its methods. However, I am facing an issue where I am unable to access the service functions and encountering an error. Error TypeError ...

Enhance your Angular project with a collection of sleek and modern solid

I'm encountering an issue with adding free Font Awesome icons to my app. I've tried using the following code: Here's a snippet from my package.json file "@fortawesome/angular-fontawesome": "^0.7.0", "@fortawesome/ ...

The panning functionality on Android devices within the Firefox browser is currently experiencing issues with both panstart and pan

Currently, I am collaborating on an Angular7 project and utilizing hammerjs version 2.0.1. One of the tasks at hand is to allow panning functionality on a map for mobile devices. After testing on various android devices, I noticed that it performs well on ...

Mastering the art of incorporating objects into templates using *ngFor Angular

Whenever I do my *ngFor loop in my HTML template, the data is displaying as [Object Object]. Below is my view with the enumerated data in the developer console: https://i.stack.imgur.com/KXmiI.png This is the snippet of my HTML code: https://i.stack.im ...

Sign up for a variety of HTTP observables subscriptions

I have a collection of Observables stored in activatedRoute.data.example and I need to listen for the most recent value emitted. private data$ = forkJoin( this.activatedRoute.data.pipe( map(({ examples }) => examples) ) ); ngOnInit(): void { ...

The 'palette' property is not found on the Type 'Theme' within the MUI Property

Having some trouble with MUI and TypeScript. I keep encountering this error message: Property 'palette' does not exist on type 'Theme'.ts(2339) Check out the code snippet below: const StyledTextField = styled(TextField)(({ theme }) = ...

Exclude a select few rows in MatSort, rather than excluding entire columns

When the user clicks on the Date column for sorting, it is required to exclude empty rows from the sorting. Empty rows are present due to the application of ngIf on those particular rows. The requirement states that rows with empty column values should eit ...

The element is automatically assigned an 'any' type due to the fact that a 'string' expression cannot be utilized to index the type 'typeof'

I am facing an issue that I am having trouble understanding. The error message reads as follows: TS7053: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'typeof The proble ...

How to apply dynamic styling to a MatHeaderCell using NgStyle?

My goal is to dynamically style a MatHeaderCell instance using the following code: [ngStyle]="styleHeaderCell(c)" Check out my demo here. After examining, I noticed that: styleHeaderCell(c) It receives the column and returns an object, however ...

Creating a ref in React with TypeScript to access the state of a child component

Is there a way to access the state of a child component within the parent component without using handlers in the child or lifting the state up in the parent? How can I utilize refs in React with TypeScript to createRef and retrieve the child's state ...

Retrieving the URL of a previous page in a Nest.js server

In our application, we utilize Angular 8 for the user interface and Nest Js server. One challenge we are facing is that when navigating to different pages within the application, the page URL includes a port number. While I am able to access this page UR ...

When working with the latest version of Angular CLI, make sure to include a @NgModule annotation in

Just a heads up: I'm diving into Angular for the first time, so bear with me if I make some rookie mistakes. The Lowdown I've got the latest version of Angular CLI up and running The default app loads without a hitch after 'ng serve' ...

Encountering difficulties when attempting to start a new project in Angular

I am encountering an issue while trying to create new in Angular, using version 6 and Node.js v8.11 Here is the console log: Unable to save binary /home/amit/demo/node_modules/node-sass/vendor/linux-x64-57 : { Error: EACCES: permission denied, mkdir ...

Is there a way to pass a token variable from the main page to an iframe without relying on a post message?

I am seeking assistance on how to transfer a variable from a parent window to an iframe. My situation is as follows: I am working with 2 Angular5 applications named A and B . Application B is loaded within Application A using an iframe. The aut ...

conceal a div in Angular when the user is authenticated

One of my tasks involves managing the visibility of a div based on whether the user is logged in. This functionality is achieved by utilizing an authentication service in Angular and tokens from Django. Component.html <a *ngIf="authService.isLoggedIn( ...

Updating Angular libraries can enhance the performance and functionality of

Within our organization, we rely on several custom Angular libraries for the majority of our projects. The issue arises when we need to update our codebase to a new version of Angular, as it requires updating all libraries simply to ensure compatibility ...

Is there a way to modify the login component to utilize the username instead of the email for logging in?

I recently developed a Spring Boot API which requires the username and password for login authentication. I am now trying to modify the ngx admin interface to accept the username instead of the email as the credential. Can anyone provide guidance on how ...