Steps for calling a function first and then canActivate():1. Begin by identifying the function you want

I have a unique condition in my AuthGuard code. If the resetpasss variable is not null, I want to navigate to the ResetPassIdComponent; otherwise, I want to navigate to the LoginFirstComponent.

Here is my implementation of AuthGuard:

export class AuthGuard implements CanActivate {
    myappurl: any;
    resetpasss: any;
    constructor(private router: Router, private auth: LoginService) {
    }
    geturl() {
        handleOpenURL((appURL: AppURL) => {
            console.log('Got the following appURL1', appURL);
            this.myappurl = appURL
            let url_1 = this.myappurl.toString();
            let url_id = url_1.split("/").reverse()[0];
            this.resetpasss = url_id
            let LS = require("nativescript-localstorage");
            LS.setItem(this.resetpasss)
            // this.router.navigateByUrl('/resetPasswordRequest/' + this.resetpasss);
            console.log('this.resetpass1', this.resetpasss)
        });
        return true;
    }
    canActivate(): boolean {
        this.geturl();
        if (this.auth.isAuthenticated()) {
            return true;
        }
        console.log('this.resetpasss2', this.resetpasss)
        this.router.navigate(['/outsidelogin/login']);
        return false;
    }
 }

When clicking a link from an email, the geturl() function is triggered. This function retrieves an id and saves it in local storage. In the canActivate() method, I create a condition for navigating to the desired component based on the saved id.

Do you have any suggestions on how to improve this condition?

This is my routing configuration:

const routes: Routes = [
  {
    path: 'home',
    component: HomeComponent,
    canActivate: [AuthGuard],
    children: [
      {
        path: 'fp', component: FirstPageComponent
      }
    ]
  },
  {
    path: 'outsidelogin',
    component: outsideloginComponent,
    children: [
      { path: 'login', component: LoginFirstComponent },
      { path: 'register', component: RegisterComponent },
    ]
  },
    { path: '', redirectTo: '/home/fp', pathMatch: 'full' },
    { path: 'resetPasswordRequest/:id', component: ResetPassIdComponent }
];

Answer №1

To implement the condition within the CanActivate() method, you can try the following approach:

canActivate(): boolean {
    this.checkURL();
    if (this.auth.isAuthenticated()) {
        return true;
    } else if(this.resetpassword){
       this.router.navigate([this.myappurl]);
    }else{
        this.router.navigate(['/outsidelogin/login']);
    }       
}

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

Angular 4 is having trouble retrieving the JSON response

When I attempt to log errors in a specific scenario and use error, the following error message is displayed: { "errors" : [ { "entity" : "Movement", "property" : "direction", "invalidValue" : null, "message" : "Il campo non può essere v ...

Avoiding duplication of jquery when using webpack and typescript

I encountered an error message that reads: Uncaught TypeError: $(...).dialog is not a function The issue appears to be arising from importing jquery twice, and I am struggling to find a solution. Additionally, the error references bootstrap in the follo ...

Exploring the combination of Angular and Redux on windows devices

Upon running ng serve, I encountered the following error: The class NgRedux<RootState> has been incorrectly implemented as interface ObservableStore<RootState>. The property [Symbol.observable] is missing in type NgRedux<RootState> but i ...

Inter-component communication through service interaction

In order to achieve reusability, I have designed two generic components known as 1)list and 2)details: Here is a visual representation of the components: https://i.sstatic.net/NYwZj.png Now, these components are being reused in other components named SC ...

JavaScript library declaration files are essential for providing type definitions and enabling

I have encountered a problem with my JS library and its declaration files (*.d.ts) in my TypeScript projects. For some reason, my TS project seems to be ignoring these declaration files. To investigate this issue further, I decided to conduct a simple tes ...

Emphasizing the chosen element in a list using angular

After retrieving an array of items from the database, my list is constantly changing, causing the HTML display to update dynamically. However, I am struggling with highlighting only the selected item in the list, as the entire list gets highlighted upon se ...

The specified property is not found on the type 'DetailedHTMLProps<ImgHTMLAttributes<HTMLImageElement>, HTMLImageElement>'

Trying to display an image in React using TypeScript is proving challenging. ... <img src="(ommitted for clarity)" width="400" heigth="400"/> ... An error is being encountered: Type '{ width: string; heigth: string; }' is not assignable ...

`Angular project not responding to HTML mouse click event`

I am a beginner with the Angular framework and currently experimenting with creating a basic button in the app.components.html file. My goal is to have this button trigger a function declared in the app.component.ts file. Initially, I used the (click) even ...

How to Customize Bootstrap Colors Globally in Angular 4 Using Code

I am interested in developing a dynamic coloring system using Angular. I have set up a service with four predefined strings: success, info, warning, and danger, each assigned default color codes. My goal is to inject this service at the root of my applicat ...

How can I achieve a result using a floating label in a .ts file?

I'm facing a simple issue that I can't seem to figure out. The problem is with a floating label in my HTML file, as shown below: <ion-list> <ion-item> <ion-label floating >Username</ion-la ...

Angular's HTTP request encountered an issue retrieving the complete response

When attempting to retrieve a full request using an HTTP POST request in Angular 8, I encountered an issue where the complete response was not being received from the frontend. The response appeared as follows: {"classname": "2A"} However, upon checking ...

Performing both HTTP requests with a single subscribe function in Angular 4

I'm facing an issue with the following code: ComputerValue: number; private subscription: ISubscription; ngOnInit() { this.getMyValue(); setInterval(() => { this.getMyValue(); }, 30000); } getMyValue(): void { this.subscription = th ...

Autocomplete feature shows usernames while storing corresponding user IDs

I am looking to enhance the autocomplete functionality in my application while also ensuring that the selected user ID is stored in the database. Specifically, I want the autocomplete feature to display user names for selection purposes, but instead of re ...

Navigating through unorganized items in Angular 9

Exploring Object Structures As I navigate through a complex object, I aim to extract all values within the ngbtypeahead. However, the challenge lies in the fact that the keys within this object are distinct, hindering my ability to retrieve these values ...

Best location for storing JavaScript files in an Ionic 2 application?

Where is the optimal location to store additional JavaScript files in an Ionic 2 application? I prefer not to include them within the automatically generated www directory. Here is an example of the directory layout for a basic Hello World Ionic 2 applica ...

Tips for integrating error management in Angular with RXJS

Implementing error handling in the use case method by using subscriptions is my goal. When an error occurs in the adapter, the handling should be done in the use case. However, in the code snippet provided below, the catch block does not seem to work pro ...

Bringing together a collection of objects connected by shared array elements

Given the types defined as: type A = { commonKey: { a: string }[] }; type B = { commonKey: { b: number }[] }; Is it possible to create the type below without explicitly specifying commonKey? type C = { commonKey: { a: string, b: number }[] } My initial a ...

When I declare a second service in the constructor, my modal service no longer opens as expected

Recently, I came across this login method in Angular: email: string = ""; password: string = ""; login() { const credentials = { email: this.email, password: this.password }; this.userService.login(credential ...

What is the best practice for making a gRPC call within a Typescript Vue.Js component?

Upon reviewing the grpc documentation, I discovered that proto files can be used to generate Node (Javascript), Typescript with the assistance of grpc_tools_node_protoc_ts, and grpc-web. Given that performance is not a critical factor in my particular situ ...

Is passportjs designed for use on the client side or the server side of a web

I'm currently implementing passport.js in my MEAN stack application to handle user login. One question that's been on my mind is where should I be utilizing passport.js for authenticating users? Should I integrate it on the client side with Angu ...