Executing a service prior to the loading of Angular 7 applications or components

Currently, I am in the process of developing an application using Angular 7. So far, everything is running smoothly as I have successfully managed API calls, JWT Token authentication with C#, and updating LocalStorage when needed during user login and logout.

However, I am facing a dilemma regarding setting up a middleware for login check within the application rather than relying on the lifecycle method - ng.onInit(). How can I accomplish this?

I am also curious if there is a way to trigger lifecycle events through an entry component or service. This would allow the application to verify the user's login status before loading any components and redirecting appropriately via Router.

Answer №1

When it comes to securing your application, Guard relies on the routes for protection. In my opinion, opting for a module/service solution would be more beneficial.

import { APP_INITIALIZER } from '@angular/core';

To implement this solution, you can follow these steps:


export function initializeApp(initializeService: YourInitializeService) {
  return () => { 
    initializeService.Initialize();
  }
}

{ provide: APP_INITIALIZER, useFactory: initializeApp, deps: [YourInitializeService], multi: true }

Answer №2

If you're working with Angular, don't forget to utilize Guard functionalities, especially canActivate Guard. Check out this helpful link for more information: https://angular.io/guide/router

To create a guard, follow this structure:

@Injectable({
  providedIn: 'root'
})
export class MyGuard implements CanLoad {
 constructor() {}

 canLoad(route: Route, segments: UrlSegment[]): Observable<boolean> | 
 Promise<boolean> | boolean {
   const x = true;
   if (x) {
     return true; // Allows access to the route
   } else {
      // Redirect as needed
     return false; // Prevents access to the route
  }
 }
}

In your routing Module, include the guard like so:

{
path: "yourRoute",
canActivate: [MyGuard],
component: YourComponent
}

For authentication needs, consider using a reliable library like ngx-auth which works seamlessly with guards: https://www.npmjs.com/package/ngx-auth

Answer №3

To enhance the security of your routing in Angular, consider incorporating an authGuardService as a middleware using the canActivate section.

For more information, refer to: https://angular.io/api/router/CanActivate

By doing so, you can prevent routes from being accessed if the conditions set by the canActivate service are not met. This is particularly useful for implementing login systems and ensuring access control without relying solely on lifecycle hooks.

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

Converting an array of date strings to a single string in JavaScript

Here is the JSON format I received with dynamic data: {"range":["2018-07-23T16:03:26.861Z","2018-07-23T16:03:26.861Z"]} Now, I need to convert this into the following format: range(20180723,20180723) Below is my code snippet : var data:Date[] = {"rang ...

Toggling the visibility of a div using JavaScript

When I click the button, I want to show and then hide a div. However, it doesn't work on the first click - only on the second click. How can I make it work on the first click? HTML <p>Click the button</p> <button onclick="myFu ...

What is the easiest way to switch the ON-OFF button and fetch data from the API?

I have completed my code to fetch data from an API upon button click, but I am now looking for a way to incorporate a toggle button for a more user-friendly and organized interface. However, I am unsure of how to implement this feature within my function a ...

What is the best way to remove jest from your system completely?

I've been trying to set up jest for testing react applications However, after installing it with yarn, I am encountering issues starting my react app in any way This error message keeps popping up, but the suggested solution didn't resolve it: ...

Angular 5 does not recognize the function submitEl.triggerEventHandler, resulting in an error

Greetings! I am currently working on writing unit test cases in Angular5 Jasmine related to submitting a form. Below is the structure of my form: <form *ngIf="formResetToggle" class="form-horizontal" name="scopesEditorForm" #f="ngForm" novalidate (ngSu ...

When a previous form field is filled, validate the next 3 form fields on keyup using jQuery

Upon form submission, if the formfield propBacklink has a value, the validation of fields X, Y, and Z must occur. These fields are always validated, regardless of their values, as they are readonly. An Ajax call will determine whether the validation is tru ...

Access the latest data within Sails' Waterline prior to the update process

When using Sails' Waterline, I am tasked with comparing the previous value to the new one and assigning a new attribute based on certain conditions. For instance: beforeUpdate: function(newValues, callback) { if(/* currentValues */.age > newVal ...

Accessing WCF REST endpoint using Ajax and transmitting data in JSON format

I have developed a Rest service in WCF (demo), which provides me with the following output: {"GetEmployeeJSONResult":{"Id":101,"Name":"Sumanth","Salary":5000}} Now, I have created an ASP.NET website where I am utilizing AJAX JSON to call this rest service ...

angularjs ng-repeat utilizing the index instead of names

Using ng-repat to populate an HTML table with an array has been causing some naming normalization issues for me. Dealing with stubborn users, I am now in search of a quick workaround. Sometimes my array AgendaItems appears as: {"Agenda Item":&q ...

Where does the injected style in the Angular build index file originate from?

I recently completed the migration of my Angular application from v7 to v12. I have a custom index file specified in my angular.json file like so... "projects": { "routes": { "architect": { "build": { ...

Guide to importing an npm package into a client-side file

Having some trouble importing the js-search npm package into my client-side .js file. The documentation suggests using import * as JsSearch from 'js-search';, but I keep getting a Uncaught TypeError: Failed to resolve module specifier "js-se ...

I can't seem to get db.collection.findOneAndUpdate() to work properly when using the

User Data { "_id" : ObjectId("60c012cc35fd3c596d61e72d"), "tags" : [ "react", "node", "js" ], "title" : "This is the updated title", "description" : "I am a skil ...

Tips for testing an Angular 2 component that integrates a third-party JavaScript library

Seeking guidance on how to properly test the component below that utilizes a 3rd party JavaScript library - import * as Leaflet from "leaflet"; export class GeoFencingComponent { map: any; constructor() { this.map = Leaflet ...

Next.js triggers the onClick event before routing to the href link

Scenario In my current setup with Next.js 13, I am utilizing Apollo Client to manage some client side variables. Objective I aim to trigger the onClick function before navigating to the href location. The Code I'm Using <Link href={`/sess ...

Node.js, Express continues to execute an if statement even if the condition is false

My goal is to determine whether the user signed in is an admin or not. User data is structured like this: [ { "isAdmin": "true", "_id": "60c6df22f25d381e78ab5f31", "name": "Admin", ...

Which is better to use: sql==true or sql===true?

Hey there, could you please take a look at this and thanks in advance! I'm currently working on developing a system for upgrading buildings in my game. I have set up a universal upgrade div that applies to all buildings. When the player clicks on a bu ...

Ways to dynamically update CSS properties (such as changing the color scheme throughout the entire application)

I have a question... If you're interested in conditional styling, the best approach is to utilize either ng-class or ng-style. However... For instance, let's say I'm an admin and I would like to customize the color of my application using ...

Is there a way to customize the color of an element within CardHeader in MUI?

Is there a way to customize the colors of {note.title} and {note.category}? I have attempted to do so by creating a theme: const theme = createTheme ({ palette: { category: { color: blue } } }) Unfortunately, this appro ...

Displaying various charts in a single view without the need for scrolling in HTML

How can I display the first chart larger and all subsequent charts together in one window without requiring scrolling? This will eventually be viewed on a larger screen where everything will fit perfectly. Any recommendations on how to achieve this? Here ...

How long does it take to delete and recreate a cloudfront distribution using AWS CDK?

I am currently undergoing the process of migrating from the AWS CDK CloudfrontWebDistribution construct to the Distribution Construct. According to the documentation, the CDK will delete and recreate the distribution. I am curious about the total duration ...