Implementing Typescript Angular CanActivate Guard

Having some difficulties with the guard on my route that has multiple conditions and too many lines of code. Is there a way to make it shorter?

export class GuardService implements CanActivate {
  constructor(private router: Router, private apiService: InfoService) { }

  canActivate(route: ActivatedRouteSnapshot): Observable<boolean | UrlTree> {
    const { id, type } = route.params;

    if (Object.keys(CustomerType).includes(type)) {
      return this.apiService.get(id).pipe(
        map((overview) => {
          if (type === 'additional' && overview.main === null) {
            return this.navigate([etc]);
          }
          return true;
        }),
        catchError(() => false)
      );
    } else {
      return false;
    }
  }
}

Facing challenges with numerous conditions in the guard code and seeking suggestions on how to simplify it. Any help would be greatly appreciated!

Answer №1

To improve readability and performance, consider reversing the first condition and combining it with the second one within the map function in your GuardService class:

export class GuardService implements CanActivate {
    constructor(private router: Router, private apiService: InfoService) { }
  
    canActivate(route: ActivatedRouteSnapshot): Observable<boolean | UrlTree> {
      const { id, type } = route.params;
  
      if (!Object.keys(CustomerType).includes(type)) {
        return false;
      }

      return this.apiService.get(id).pipe(
        map((overview) => {
          if (type === 'additional' && overview.main === null) {
              return this.navigate([etc])
            }
            return true;
        }),
        catchError(() => false)
      );
    }
}

Answer №2

If you want to make it a bit shorter without making a big difference

canActivate(route: ActivatedRouteSnapshot): Observable<boolean | UrlTree> {
    const { id, type } = route.params;

    if (!Object.keys(CustomerType).includes(type)) {
      return false;
    }

    return this.apiService.get(id).pipe(
        map((overview) => {
          if (type === 'additional' && overview.main === null) {
              return this.navigate([etc])
          }
          return true;
        }),
        catchError(() => 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

Transitioning from Angular 4 to 5: "Encountered NodeInvocationException: PlatformRef provider not found!"

I recently updated an Angular app from version 4.2 to 5, but encountered this error message: unhandled exception occurred while processing the request. Specifically: NodeInvocationException: No provider for PlatformRef! Error: No provider for Platfor ...

Tips for resolving conflicts between sequelize and angular within a lerna monorepo using typescript

Managing a monorepo with Lerna can be quite challenging, especially when working with both Node.js and Angular in the same project. In my setup, Angular is using "typescript": "~3.5.3". For Node.js to work seamlessly with Sequelize, I have the following ...

Table with a responsive c3 chart

Is there a way to integrate a responsive C3 chart into a table? I am trying to set up a table with a responsive layout, where one of the cells contains a C3 chart. The initial dimensions of the cell are 200 width and 50 height, but I want the chart to upd ...

The origin of the setTimeout() with an extensive delay of 99999000 cannot be located - zone.js macrotask in Angular revision 17

I'm currently facing a challenge in my Angular 17 application where I am trying to resolve a warning: NG0506: Angular hydration expected the ApplicationRef.isStable() to emit true, but it didn't happen within 10000ms. Angular hydration logic de ...

Extracting types from a union of Boxes in Typescript

Is there a way to extract boxed types from a Union that includes both boxed and raw values? class Box<T> {}; type United = Box<number> | Box<string> | boolean; type Unboxed<T> = ??? type ExtractUnited = Unboxed<United>; // n ...

Using a static value in the comparator is necessary for Array.find to function properly in Typescript

Looking to retrieve an item from an array: const device = this.selectedDevtype.devices.find(item => console.log(this.deviceID); return item.device_id === this.deviceID; }); console.log(device); When this.deviceID is logged, it shows "4", but t ...

Angular Universal API/http-request encounters "404 not found" error within Docker Image

I have an Angular application that was developed externally, featuring Angular Universal. Within this project, there are already two API domains set up (referred to as api-url-1 and api-url-2), and I recently added a third one called new-api-url. To integr ...

Tips for instructing kysely key-gen to utilize basic data types for mapping database tables

While using the kysely-codegen tool to automatically create all models from my database, I have noticed a peculiar behavior. It seems to be adding a Generated type to every field instead of generating only number or boolean. Any idea why this is happening? ...

Checking for changes in Angular text area using pipes is a common task. To do this,

I am encountering an issue with a text area containing formatted json. Users are allowed to make changes in the text area, but due to the json pipe, I cannot use [(ngmodel)}. In addition, (change) and (ngModelChange) do not appear to trigger anything. How ...

Merging the Outcomes of Observables to Create a Unified Array

I have an Observable containing items that I want to transform using the `map` operator and then use each transformed item to call another Observable. As this second Observable is being called, I need to store its results in an array. Ultimately, I wish to ...

Displaying search results in various Angular components

On my home page (homePageComponent), I have a search feature. When the user clicks on the search button, they are redirected to a different page called the search list page (searchListComponent). Within the searchListComponent, there is another component c ...

Encountering Angular 2 RC5 Routing Problem when Loading Several Modules

I am having trouble loading a child module within another child module, as shown in the image below: List of modules with routing info When I attempt to load the "Material Module" child module, which has its own routes, within the "Home Module," I encoun ...

How to retrieve the type of a computed keyof T as a generic type within TypeScript

I am working with two different interfaces: interface PersonRequirements{ user:string, password:string, id:number } export interface Requirement<R> { name: keyof R & string, save: () => any,/* I want this return type to be ...

Invoke a function upon subscription in Angular

I have a requirement to trigger a method after a window resize event, but with a 500ms delay. I have implemented it as shown below and it seems to be working fine. However, being new to Angular, I am curious to know if there is a better way to achieve th ...

Guide to integrating Gandi.Net API with Node.js in server.js

I'm a beginner in Node.Js and I'm currently working on creating a Mean Stack application. One of the things I need to do is call a 3rd party API, specifically Gandi.Net, from my Node.js code. My Node.Js and Express Application are being used to ...

Seeking a guide on how to effectively utilize Angular 6 for consuming REST API and performing CRUD operations

I am a beginner with Angular and I am currently using Version 6, specifically the CLI tool. My main focus right now is learning how to make REST API calls. I have searched for tutorials on this topic but unfortunately, none of them have been successful fo ...

Is it possible to begin utilizing Angular 2 without requiring Node?

I am interested in experimenting with using angular 2 for VS 2015, however, the first requirement is having node.js. To my understanding, do I need node.js as a web server and npm to download packages? Is it possible to achieve the same goal using IIS an ...

Enroll in various Observers simultaneously using a loop in Angular

Currently, I am facing an issue in my code. The scenario is as follows: I need to iterate through an array of objects (orders) and perform some processing on each order. After that, I have to make multiple API calls for each product within the order' ...

Find out the quantity of enum elements in TypeScript

Exploring the realm of TypeScript, one may wonder about determining the number of elements in an enum. Consider this example: enum ExampleEnum { element1 = 1, element2 = 2, element3 = 3, element4 = 4, element5 = 5, element6 = 6 } ...

Is your Typescript compilation running into a problem with jwt tokens?

Having issues while trying to compile a typescript file as the compiler is throwing an error message: Error: TS2339 - The property 'payload' does not exist on type 'string | object'. Property 'payload' does not exist on type ...