Securing components in Angular2 with login verification

After wrapping multiple components' ngInit with a check to verify if users are logged in or not, I am looking for a way to avoid repeating the same code.

export class ComponentX implements OnInit {
    constructor(private _authService: AuthService) {}
    ngOnInit() {
       if(this._authService.isLoggedIn()) {
          // Do stuff
       }
       else {
         // Redirect to login page
       }
    }
}

I want to consolidate this if check into a single location that can be easily applied to any components as needed. How can I achieve this?

Answer №1

According to Günter's recommendation

import { Injectable } from '@angular/core'
import { Router, CanActivate } from '@angular/router'
import { AuthUtils } from "./authUtils.service"


@Injectable()
export class AuthGuard implements CanActivate {
  constructor(private _router: Router, private _authUtils: AuthUtils) {}

  canActivate(): boolean {
    if(this._authUtils.isLogged()) {
        return true
    }
    else {
        this._router.navigate(["/login"])
        return false
    }
  }
}

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

Styling of Bootstrap HTML element not appearing as expected

Recently, I've been trying out a new approach by embedding Bootstrap components in an iframe. However, despite loading the necessary stylesheet and scripts, the elements seem to be missing their styles. Can anyone shed some light on why this might be ...

What is the process for including a selected-by option in a VIS network graph?

I'm trying to outline the neighboring nodes of the node that has been selected (highlightNearest). https://i.sstatic.net/lynhu.png Unfortunately, I haven't had success achieving this using JavaScript. Link to StackBlitz ...

Implementing a post method in Angular without a request body

I've been attempting to send a JSON request and handle the response, but I keep encountering these errors: zone-evergreen.js:2952 OPTIONS http://'api':10050/api/content/Delivery net::ERR_EMPTY_RESPONSE core.js:6014 ERROR HttpErrorResponse ...

In this guide, we will explore the process of designing unique styles for ng

What is the proper way to customize CSS for a specific element? &.ng-select-focused { &:not(.ng-select-opened) > .ng-select-container { border-color: $ng-select-highlight; box-shadow: $ng-select-box-shadow; } } The offi ...

Upon transitioning from typescript to javascript

I attempted to clarify my confusion about TypeScript, but I'm still struggling to explain it well. From my understanding, TypeScript is a strict syntactical superset of JavaScript that enhances our code by allowing us to use different types to define ...

Encountering issues while attempting to transmit several files to backend in React/NestJS resulting in a BAD REQUEST error

My goal is to allow users to upload both their CV and image at the same time as a feature. However, every time I attempt to send both files simultaneously to the backend, I encounter a Bad Request error 400. I have made various attempts to troubleshoot th ...

Having trouble with npm install on an Angular project? It seems to be failing with an ECONNREFUSED error while trying to

I am facing an issue while trying to clone one of my Angular projects. To make it work, I need to run npm install, which used to work fine in the past. However, recently I encountered the following error: npm install npm ERR! code ECONNREFUSED npm ERR! ...

Retrieve the radio button value without using a key when submitting a form in JSON

Looking to extract the value upon form submission in Angular, here is the code: In my Typescript: constructor(public navCtrl: NavController, public navParams: NavParams, public modalCtrl: ModalController, public formBuilder: FormBuilder, public alertCtrl ...

What is the best way to arrange map elements in a React application?

I am trying to implement filter buttons for low to high rates and high to low rates, but I am having trouble figuring it out. How can I apply the filter to display the data accordingly? The data that needs to be filtered is stored in rate.retail_rate. ty ...

Attempting to retrieve a value from a bespoke store in Svelte

Let me pose a question: I have created a custom store that looks like this: const MyCustomStore = (Data) => { const { subscribe, set, update } = writable(Data); return { subscribe, update, set, setData: (NewData) => { set(Ne ...

The Angularfire library encountered an issue when trying to access the 'push' property of a null object

I am currently in the process of creating a new object in the database for an assessment. Right now, I have hardcoded it to test its functionality, but ultimately, it will be dynamic based on user input from the view. However, I am encountering an error th ...

Having trouble retrieving an Enum within an Angular template?

I am trying to use an enum to read a property of an array. However, I encountered an error with the following code: <ng-container *ngFor="let elem of list"> <div class="ui-g-12 ui-sm-12 ui-md-12 ui-lg-12 ui-xl-12"> &l ...

Preventing Firebase duplicates leads to the error of not being able to read the property 'apps'

Struggling to incorporate Firebase into a TypeScript/NextJS project, I have encountered difficulties. Despite successfully importing and initializing the app: import * as firebase from "firebase/app"; import { collection, getDocs } from "fir ...

Troubleshooting: @HostListener for window scroll event not functioning as expected

Having trouble creating a sticky header that stays fixed when scrolling down in an Angular 4 application. The scroll event is not being detected. The header is located in the layout component, while the content I want to be scrollable is placed in the rou ...

In Typescript, it is not possible to assign the type 'any' to a string, but I am attempting to assign a value that is

I'm new to TypeScript and currently learning about how types function in this language. Additionally, I'm utilizing MaterialUI for this particular project. The issue I'm encountering involves attempting to assign an any value to a variable ...

Terminate the operation of an active script tag within Angular 11

At the moment, my Angular component is utilizing the Renderer2 library to insert a series of script tags into the DOM. These scripts are sourced externally and I am unable to alter their content. Below is a snippet where the scripts array contains the link ...

Utilizing a React npm component within an Angular project: A step-by-step guide

After successfully creating a simple react component and publishing it to the NPM registry, I encountered an issue when trying to use the same plugin in an Angular project. The custom plugin can be found at: https://www.npmjs.com/package/reactcustomplugin ...

What is the most effective approach for annotating TypeScript abstract classes that are dynamically loaded?

I am in the process of developing a library that allows for the integration of external implementations, and I am exploring the optimal approach to defining types for these implementations. Illustration abstract class Creature { public abstract makeN ...

Using TypeScript to define a static enum within a React functional component

Creating a React.FunctionalComponent with static props: import MyAwesomeComponent from './MyAwesomeComponent'; ... <MyAwesomeComponent mode={MyAwesomeComponent.modes.superAwesome} /> Static props defined as key-value pairs: MyAwe ...

Utilizing an image as a background using [ngStyle] in Angular 5

I attempted to set the background of a Div element with an image saved in the database using [ngStyle] in Angular, but unfortunately it did not work as expected. <div class="image" [ngStyle]="{'background': ' url(' + imageUrl + &ap ...