Protector of the young travelers' paths

I have encountered a recurring issue with implementing Guards on my pages.

Despite referencing multiple solutions from StackOverflow, none of them seem to work for me. Take this example for instance.

This is my first attempt at restricting access to certain pages using Guards, specifically child pages within my Truck module:

Truck
  |_ truck-list
  |_ truck-search
  |_ truck-menu
  |_ truck-details

In my route file for the Truck module, I have specified Paths and corresponding components as follows:

RouterModule.forChild([
    {path: 'list', component: TruckListComponent, canActivate: [TruckGuard]},
    {path: 'search', component: TruckSearchComponent, canActivate: [TruckGuard]},
    {path: 'details/:id', component: TruckDetailsComponent},
    {path: 'menu', component: TruckMenuListComponent},
    {path: 'menu/:id', component: TruckMenuListComponent},
    {path: 'menu/add/:id', component: TruckMenuAddComponent},
    ])

I have also defined routes in my app-routing module covering various components including the Truck module itself:

const appRoutes: Routes = [
    // List of paths...
  ];
...

To manage these routes for the Truck module, I created a Truck.guard.ts file which includes methods for CanActivate and CanActivateChild:

export class TruckGuard implements CanActivate, CanActivateChild {
  // Guard implementation...
}

Currently, only the path truck/list seems to be functioning correctly, redirecting to the forbidden page when required. However, all other paths fail to do so.

I am puzzled by this inconsistency despite employing both canActivate and canActivateChild functions. Any insights or assistance would be greatly appreciated.

Answer №1

There are a few errors in your setup that need to be corrected.

  1. The reason why the truck/list route is functioning correctly is because you have applied the canActivate guard specifically to it, but not to the other routes.

     {path: 'list', component: TruckListComponent, canActivate: [TruckGuard]},
    

Additionally, in your canActivate method, you are only checking for the truck/list path.

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
let url = window.location.pathname;

if((url == '/truck') && this.authService.isCustomer()){
  return true;
}
else{
  this.route.navigate(['app-forbidden']);
  return false;
}

}

  1. The reason why the other routes are not working is because you have not applied the canActivateChild guard to the parent module.

To fix this, add a canActivateChild to the appRoute as shown below:

const appRoutes: Routes = [
{ path: '', component: HomeComponent},
{ path: 'app-forbidden', component: ForbiddenComponent},
{ path: 'Home', component: HomeComponent},
{ path: 'About', component: AboutComponent},
{ path: 'forbidden', component: ForbiddenComponent},
{ path: 'Login', component: LoginComponent},
{ path: 'Logout', component: LoginComponent},
{ path: 'confirmation-commande/:message', component: ConfirmationCommandeComponent},
{ path: 'orders', component: OrderListComponent},
{ path: 'truck/search', component: TruckSearchComponent},
{ path: 'SignUp/customer', component: UseraccountCreateCustomerComponent},
{ path: 'SignUp/truck', component: UseraccountCreateTruckComponent},
{ path: 'useraccount', loadChildren: () => 
import('./useraccount/useraccount.module').then(u => u.UserAccountModule)},
// Truck module Your canActivateChild comes here    
{ path: 'truck', loadChildren: () => import('./truck/truck.module').then(t=> t.TruckModule)}, canActivateChild:TruckGuard // <<< HERE
{path: 'location', component: TruckLocationComponent},
{ path: '500', component: InternalServerComponent },
{ path: '', redirectTo: '/home', pathMatch: 'full' }

];

Answer №2

After much troubleshooting, the solution was found by adding "canActivateChild" in the app-module.ts file:

 { path: 'truck', loadChildren: () => import('./truck/truck.module').then(t => t.TruckModule), canActivateChild: [TruckGuard]},

Furthermore, the URL is tested within the guard file using state: RouterStateSnapshot instead of window.location.pathname. See below for the updated code snippet:

 if((state.url == '/truck/list') && this.authService.isCustomer()){
      return true;
    }
    else if((state.url == '/truck/search') && this.authService.isCustomer()){
      return true;
    }
   else if((state.url == '/truck/menu') && this.authService.isCustomer()){
      return true;
    }
    else if((state.url == '/truck/menu/' + childRoute.params['id']) && this.authService.isCustomer()){
      return true;
    }
    else if((state.url == '/truck/details/' + childRoute.params['id']) && this.authService.isCustomer()){
      return true;
    }
    else if((state.url == '/Login') && this.authService.isCustomer()){
      return true;
    }
    else{
      this.route.navigate(['app-forbidden']);
      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

Angular2 - the pipe was not located while organizing records

I've successfully fetched data from an API and displayed it in the view, but I'm struggling to organize the data by date. Whenever I attempt to do so, I encounter this error message: The pipe 'groupBy' could not be found pipe.ts impor ...

Deleting the First Item from an Array in Typescript using Angular

Clicking my Button in .html <button (click)="deleteFirst()">Delete First</button> My array setup and removal function in .ts: people = [ {first: "Tom", last: "Brown"}, {first: "Ben", last: &qu ...

What is the best way to utilize a single component for validating two other components?

I am encountering an issue with my components setup. I have three components in total: GalleryAddComponent, which is used to add a new element, GalleryItemComponent, used to edit an element, and FieldsComponent, the form component utilized by both GalleryA ...

Navigating an object in TypeScript: the right approach

Curious if there might be a bug in TypeScript? Just seeking clarification on whether my code is incorrect or if there is an actual issue with the language. interface Something { key1: string; key2: number; key3: boolean; } const someObject: S ...

What are the benefits of dealing with various versions of Angular?

Currently, I am using Angular version 8.2.14 which was installed globally by running the command npm install -g @angular/cli. All my projects are also built on this same version of Angular. With the recent release of Angular version 9, I am contemplating ...

Error message: The provider is not being recognized by react-redux while using NextJS with RTK and

Struggling to integrate Redux RTK into my Next JS 13.4 app has been quite the challenge. No matter how many tutorials I follow, I keep encountering the same error in my provider.ts file. 'use client' import { store } from './store'; imp ...

When importing a module, the function in the ts file may not be recognized or located

While attempting to create a VSTS (Azure Devops) Extension, I encountered a perplexing issue. Within my HTML page, I have a button element with an onclick listener: <!DOCTYPE html> <head> <script type="text/javascript"> VS ...

Angular - The argument provided is not compatible with the parameter

I encountered the following TypeScript errors in app.component.ts: Issue: Argument of type '(events: Event[]) => void' is not assignable to parameter of type '(value: Event[]) => void'. Description: Types of parameters 'e ...

Experiencing difficulties in constructing a project through Angular-CLI on a Windows operating system

Encountering an error while attempting to install angular-cli with the command: npm install -g angular-cli The error message received is as follows: npm ERR! Windows_NT 10.0.14393 npm ERR! argv "C:\\Program Files\\nodejs\\n ...

Exploring the Potential of Using ngIf-else Expressions in Angular 2

Here is a code snippet that I wrote: <tr *ngFor="let sample of data; let i = index" [attr.data-index]="i"> <ng-container *ngIf="sample.configuration_type == 1; then thenBlock; else elseBlock"></ng-container> <ng-template #t ...

React modal not closing when clicking outside the modal in Bootstrap

I recently utilized a react-bootstrap modal to display notifications in my React project. While the modal functions correctly, I encountered an issue where it would not close when clicking outside of the modal. Here is the code for the modal: import Reac ...

Creating a function in Typescript to extend a generic builder type with new methods

Looking to address the warnings associated with buildChainableHTML. Check out this TS Playground Link Is there a way to both: a) Address the language server's concerns without resorting to workarounds (such as !,as, ?)? b) Dodge using type HTMLChain ...

Error NG8001: The element 'router-outlet' is not recognized: Make sure that 'router-outlet' is a component in Angular, and confirm that it is included in this module

Having trouble running ng serve or ng build due to an error message stating that 'router-outlet' is not a recognized element. The Angular application structure looks like this: app.module.ts: import { NgModule } from '@angular/core'; i ...

What is the best way to maintain scrollbars on mobile devices?

I'm currently building a cross-platform application using Angular 4 that needs to work seamlessly on both mobile and desktop devices. Is there a special trick to prevent the scrollbars from disappearing when viewing this page on a mobile browser? I&ap ...

When using Angular server-side pagination with ngrx and Express in Node.js, I often encounter discrepancies in the indexing across different stacks

After successfully implementing server-side pagination in Angular, I encountered an issue where the page was set to 1 initially, but the mat-paginator component started at index 2. Despite functioning correctly when changing pages, this discrepancy puzzled ...

Checking for file existence using the HEAD command can be done by specifying the file path as

I am seeking to utilize the Spring Endpoint provided below for file uploading. @PostMapping(value = "/upload", produces = { MediaType.APPLICATION_JSON_VALUE }) public ResponseEntity<StringResponseDTO> uploadFile(@RequestParam("file") MultipartFi ...

What is the best way to retrieve the current value of an *ngFor loop upon button click?

I have been attempting to retrieve the data.login value of the data item that the user has clicked on the avatar image. Despite my efforts, I have not been able to successfully achieve this through various methods found online. How can I access the current ...

Tips for incorporating state properties into a component

Currently engrossed in a project revolving around state management for individual components utilizing Angular 7 and NGRX. The challenge at hand is to ensure scalability of the implementation, allowing multiple uses while maintaining independence. Thus fa ...

The useState variable's set method fails to properly update the state variable

I am currently developing an application with a chat feature. Whenever a new chat comes in from a user, the store updates an array containing all the chats. This array is then passed down to a child component as a prop. The child component runs a useEffect ...

Encountered issue in Angular: Object prototype must be either an Object or null, not undefined

I encountered an issue with my Angular application when trying to install npm dependencies using npm i. I kept receiving a "sha1 seems to be corrupted" error. To resolve this, I deleted the package-lock.json file and was able to successfully install all th ...