requirements for navigating within an Angular application

Initially, if the first user is already logged in on the first tab and is redirected to the dashboard, when that same user opens a second tab in the same browser (by pasting the login URL), they are automatically redirected to the dashboard without having to go through the login page. I encountered an issue where there are specific routes on the login page that only unauthenticated users can access.

In the login.component.ts

linkToMarket(): void {
    this.sidenav.close().then(() => {
        this.router.navigate([UrlConstants.Market]);
    });
}

On the Market page (in the second tab), the user can return back to the login page, but unfortunately, they are redirected through the dashboard (as the first user is already logged in) due to the [redirect to dashboard if user is logged in][1] feature. How can I ensure that if there is a different user on the second tab, when returning from the market page, they will not be redirected to the dashboard but instead to the login page? Should I implement a condition on the route or use AuthGuard (CanActivate)?

Detail of login component

ngOnInit(): void {
    if (this.authenService.isUserAuthenticated()) {
        this.router.navigate([UrlConstants.UserSetting])
    }
}

market.component.ts

linkToSignIn(): void {
    this.router.navigate([UrlConstants.Login], { queryParams: { returnUrl: UrlConstants.Market } });
    if (this.authenService.isUserAuthenticated()) {
        this.router.navigate([UrlConstants.Login])
    }
}


[1]: https://stackoverflow.com/questions/44121164/angular-2-redirect-if-user-is-logged-in

Answer №1

I'm a bit confused about the situation involving the first and second user in your query.

In general, one way to safeguard specific routes that require authentication is by utilizing a route guard. The primary role of a route guard is to ensure that access to a certain route is restricted unless certain conditions are met (such as being logged in).

Below is an example of an authentication guard I have implemented:

import { Injectable } from '@angular/core';
import { CanActivate, CanLoad, ActivatedRouteSnapshot, RouterStateSnapshot, Router, Route } from '@angular/router';

import { Observable } from 'rxjs';

import { AuthService } from './auth.service';

@Injectable({
  providedIn: 'root'
})
export class AuthGuard implements CanActivate, CanLoad {

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

  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
    return this.checkLoggedIn(state.url);
  }

  checkLoggedIn(url: string): boolean {
    if (this.authService.isLoggedIn) {
      return true;
    }

    // Store the attempted URL for redirection
    this.authService.redirectUrl = url;
    this.router.navigate(['/login']);
    return false;
  }

}

To implement this guard, you need to attach it to the route configuration like so:

  {
    path: 'products',
    loadChildren: './products/product.module#ProductModule',
    canActivate: [AuthGuard],
    data: { preload: false },
  },

Does this address your inquiry?

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

Could you explain the significance of the typscript parameters encapsulated within curly braces?

I'm confused about the syntax in this TypeScript code snippet. Why is the data parameter enclosed in curly braces and followed by a colon and the same data object with a type specification? Can someone explain what this means? addArrivingTruckSuggesti ...

The map buttons are located underneath the map, and unfortunately, it seems that setting the map height to 100% using Angular is

Upon completing the creation and display of the map, an unusual occurrence is taking place where the map buttons ("Zoom rectangular, map settings, and scale bar") are appearing below the map as oversized icons. Additionally, there is a challenge when setti ...

The Reason Behind Angular Error when Using CSS Custom Tags

I have the following SCSS code: main{ width: 100%; height: 840px; /*background: red;*/ margin: 10px auto; position: relative; padding: 5px 0; } section{ width: 98%; height: 600px; margin: auto; display: flex; ...

When the component I created for dark mode is clicked, the colors in react-tsparticles change dynamically

I am looking to modify the theme of the react-tsparticle component function Particle() { const particlesInit = (main) => {}; const particlesLoaded = (container) => { <DarkMode />; container.loadTheme("dark&q ...

The positioning of the Zorro table column remains flexible despite the presence of nzLeft

I am currently developing a project using Angular. Within one of my components, I have a table that displays some data. This table is generated by the ng-zorro table module. However, I've encountered an issue where setting a table column or header wi ...

What is the process for updating the authService in Angular to return an observable using the map function from the previous version?

I recently followed a tutorial on JWT authentication with ASP.NET Core 2 Web API, Angular 5, .NET Core Identity, and Facebook login. The tutorial can be found here. While the tutorial was well-written, it utilized an older version of Angular (I am using An ...

Adjusting ngClass dynamically as values change

Currently, I am facing a situation where I want to dynamically add a class to my view using ngClass based on changes in the output value. The output value is dependent on the response received from an API, and I am fetching data from the endpoint every sec ...

Tips on transforming a JSON array object into a JSON array

**Background:** I have been utilizing lodash to eliminate the empty key from my JSON data. However, upon removal of the keys, it transforms my array into an object. For instance: { "projection": "Miller", "series": [ { "mapPolygons": { ...

What are the specific purposes of utilizing semantic versioning (semver) notation within the package.json file?

Could someone clarify the specific distinctions between the semver notations found in package.json file? I'd appreciate a detailed explanation. ...

Bringing a JavaScript file into an Ionic/Angular 2 project

I have been attempting to integrate a simple JS library into Angular 2. The library in question is JIC.js. var jic = { /** * This function takes an Image Object (JPG or PNG) and returns a compressed new Image Object * @param {Ima ...

Definition for a function within a specific namespace that returns the specified object

Seeking to define the type of a function within a namespace (L.DomEvent.on(e)) that returns this, I encountered an issue with my JavaScript source code: L.DomEvent = { // @function on(el: HTMLElement, eventMap: Object, context?: Object): this on: ...

What is the method for adjusting the font size of the label in an Angular mat-checkbox element?

I've been trying to adjust the font size of a mat-checkbox's label, but no matter what I do, the component's default styles keep overriding my changes: Using !important Trying ::ng-deep Applying a global style in styles.scss <mat-checkb ...

Can wildcard paths be imported in React using Typescript?

Is there a way to dynamically import a React Typescript Component from a wildcard path, similar to the following code snippet? const Component = loadable( () => import(`../../../src/**/*/${component_name}`), ); I have searched numerous solutions on ...

getItemForm does not make a second promise call

I have a scenario where my function calls the api.send service twice, however when I run a test expecting it to resolve both promises, only res1 is returned and not res2. How can I ensure that both promises are resolved successfully? Here is my function: ...

The 'items' property cannot be linked to 'virtual-scroller' as it is not a recognized attribute

I'm currently facing an issue with integrating virtual scroll into my Ionic 4 + Angular project. Previously, I relied on Ionic's implementation of virtual scroll (ion-virtual-scroll) which worked well initially. However, I encountered a major dr ...

How can I implement a feature in Angular where clicking the edit button loads a form (in a separate component) pre-populated with previous data, along with an update button for

Within the employee-list component, there is a table displaying a list of employees. This table includes an option to edit details. <button type="button" class="btn btn-primary" routerLink="../create-employee">Edit</b ...

What is the functionality of angular-cli@webpack?

After working with angular-cli using systemJS, I have become comfortable with the build process, test cases, and component interaction. Recently, I made the switch from angular-cli to angular-cli@webpack. However, I am now facing confusion on a few point ...

Limitations of MaterialUI Slider

Looking for a solution to distribute 350 points across 8 sliders, each with a range of 0-100 and 5 marks at 0, 25, 50, 75, and 100. With each step consuming or returning 25 points, the challenge lies in allowing users to adjust the points allocation withou ...

Unable to execute @angular/cli following installation

I recently set up the @angular/cli on my MacBook. The Node server version I am using is v6.9.5 and npm version 3.10.10. To install the @angular/cli, I executed the command below: sudo npm install -g @angular-cli However, whenever I try to run any ng co ...

Tips for replacing HTTP response in Angular 4

One of my challenges involves using a specialized HttpService that inherits from Angular's native Http: export class HttpService extends Http { } I am trying to figure out how to intercept/override the response: My attempt to do this looks like: r ...