Navigating to various components upon the initiation of an Angular app

I am currently working on an Angular application where the user experience varies based on the user's role. The user can either be a customer or an admin.

Within my routing module, I have set up the following routes:

{path: '', redirectTo: 'admin-portal', pathMatch: 'full'},
{path: 'admin-portal', component: AdminPortalComponent, canActivate: [AuthGuard]},
{path: 'customer-portal', component: CustomerPortalComponent, canActivate: [AuthGuard]}

My goal is to fetch a variable from local storage upon app load and use it to determine where to redirect the user. I am considering implementing a condition like

{path: '', redirectTo: 1===1 ? 'admin-portal' : 'customer-portal', pathMatch: 'full'}

Answer №1

To implement a guard in your Angular application, you can create another guard and define the conditions inside it.

    @Injectable()
    export class AuthGuard implements CanActivate {
      constructor(private router: Router) {

      }

      canActivate(next: ActivatedRouteSnapshot,
                  state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
        if(1===1){
           this.router.navigate(['admin-dashboard']);
           return false;
         }else{
           this.router.navigate(['user-dashboard']);
           return false;
        }

      }
    }

Next, you need to specify this guard in the route configuration as shown below:

{path: '', pathMatch: 'full', component: HomeComponent, canActivate: [AuthGuard]}

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

Enhancing the angular-ui-bootstrap typeahead module

Currently, I am using the typeahead feature from angular-ui-bootstrap to allow users to select a person's name or add a new name if it is not available in the options. I have customized the getMatchesAsync function with the following code: if(scope ...

Make sure to load all necessary resources prior to loading the webpage

My inquiry is as follows: I have a single webpage containing numerous images in both small and large resolutions, utilized in HTML and CSS (e.g., as background images in CSS classes). Currently, I am looking to preload all the images on my site before it ...

Caution: The absence of FIREBASE_CONFIG and GCLOUD_PROJECT environment variables may result in the failure to initialize firebase-admin

I followed a tutorial to set up the Firebase Admin SDK. https://firebase.google.com/docs/admin/setup I downloaded a JSON file (service account) from the Firebase console located at: C:\ct\functions\src\cargo-tender-firebase-adminsdk- ...

What could be causing the issue of CSS Styles not being applied to an Angular 2 component with Vaadin elements?

Currently, I am immersed in the tutorial on Vaadin elements using Angular 2 that I stumbled upon here In section 5.3, Styles are applied to the app.component.ts as shown below import { Component } from [email protected]/core'; @Component({ select ...

Updating a Nested Form to Modify an Object

There is an API that fetches an object with the following structure: { "objectAttributes": [ { "id": "1", "Name": "First", "Comment": "First" }, { "id": "2", "Name": "Second", "Comment": "Second" } ] ...

Assigning a value to an attribute as either a "string" or null within JSON Schema while specifying a maximum length

I'm currently working on crafting a JSON schema that supports a nullable attribute. I am aiming to have the ability for specific JSON structures like this one be considered valid: { "some_name" : null } This is how my schema looks like: { "type" ...

Exploring the process of retrieving enum values in AngularJS using response data

I am facing an issue with fetching enum values in AngularJS. In my table list, the 'Criteria Type' column displays either 'C' for Cost or 'B' for Benefit, retrieved from MySQL. How can I convert the initial string 'C&apos ...

Experimenting with parallelism using TypeScript/JS

Currently, I am tackling a TS project that involves testing concurrent code and its interactions with a database, specifically focusing on idepotency. My goal is to ensure that multiple requests modifying the same resource will either apply changes correct ...

Assign the value from a drop-down menu to an SQL variable dynamically without the need for a submit button

I am trying to retrieve the value of the selected item in a drop-down menu populated from an SQL database. This value is essential for me to formulate the SQL statement required to access a specific record. The drop-down menu has already been populated. S ...

What steps are involved in integrating OpenCV into a JavaScript project?

After recently installing OpenCV via npm using this guide: https://www.npmjs.com/package/opencv I'm facing a simple question. How can I actually utilize the OpenCV library in my project? The site provides a face detection example code snippet: cv.r ...

JavaScript: A guide to calculating the average of a JSON array using certain criteria within the keys/fields

I have a scenario where I need to calculate the average values of specific keys in an array: const users = [ { name: 'Adam', age: 20, country: 'France', weight: 100 }, { name: 'Adam', age: 28, country: 'Germany' ...

Guide on extracting part of a string in JavaScript from a specific starting point to a designated character

Currently working on a JavaScript project where I am in need of extracting words enclosed within two brackets. For example: [Green]- Amazon I specifically require the word "Green" from within the brackets. Using indexOf() won't work as there could ...

Pass a personalized header during preflight request OPTIONS in angular version 5

I have recently developed an Angular 5 app that communicates with a REST API built using Golang and hosted on an AWS EC2 instance running on port 8080. When my angular front-end code sends a POST request, the browser initiates a CORS preflight request, but ...

What is the best way to assign a class to multiple Angular custom directives simultaneously?

In the process of developing my application, I have implemented various custom directives and I am concerned about ensuring they are displayed correctly across all modern browsers. I am considering whether there is a point in the angular lifecycle where I ...

Ensure the content is optimized for all screen sizes, utilizing Bootstrap to adapt accordingly

I have a webpage with a header, a footer, and a container id="item" that contains a list of four items with their respective logos. I am attempting to make the item container responsive based on the screen size so the entire page fits the screen without re ...

The error message "Property 'toBeInTheDocument' is not recognized by type 'JestMatchers<HTMLElement>'" is encountered when using Webpack 5 and Jest

I've been struggling to configure Jest typings with Webpack 5 and TypeScript. Even after trying various solutions, the issue persists only with "screen" and "toBeInTheDocument" in my test example below. My suspicion is that it's related to an ESL ...

Clear a variable that was sent through the post method in an ajax call

Within my JavaScript file, I have the following Ajax code: // Default settings for Ajax requests $.ajaxSetup({ type: 'POST', url: path + '/relay.php' + '?curr=' + currency + "&ver=" + Ma ...

Mongodb Retrieving results and their opposites

Can you retrieve results that match a specific query and those that do not in a single query? Assume I have the following data: { name: 'name1', age: 19 }, { name: 'name2', age: 20 }, { name: 'name3', ...

Is there a way to showcase a modal following a timed delay?

I want my modal to appear 2 seconds after the page loads. I've tried setting the state in componentDidUpdate, but I keep getting active: undefined. The active props control the visibility of the modal on the page. When I toggle it to true using the Re ...

problem encountered when transferring data using ajax

I'm struggling with figuring out how to use an ajax function My goal is to send PHP variables via ajax to another page when a user clicks on a link Javascript function sendData(a, b, c, d) { $.ajax({ url: "page.php", typ ...