How to transfer data from a lazy-loaded Angular module to a CanActivate service using the router?

/* Routes Configuration */
import { RouterModule } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { ShopComponent } from './home/shop.component';
import { DataResolver } from './data-resolver';

const routes = [
    {
        path: 'home',
        canActivate: ['canActivateservice'],
        children: [
            { path: 'contact', loadChildren: './src/contact/contact.module#ContactModule' },
        ]
    },
    { path: 'about', loadChildren: './src/about/about.module#AboutModule' },
    { path: '', component: HomeComponent }
];


export default RouterModule.forRoot(routes);

In the code snippet above, we are loading the contact module and using a canActivate guard.

import { Route, RouterModule } from '@angular/router';
import { ContactComponent } from './contact.component';
import { MapComponent } from './map.component';
import { DefaultComponent } from './default.component';

export const ContactRoutes: Route[] = [
    {
        path: '',
        data: { id: '1', desc: 'foo' },
        component: ContactComponent,
        children: [
            { path: '', component: DefaultComponent },
        ]
    }
];

export default RouterModule.forChild(ContactRoutes);

In the code above, we are passing data from this module.

 canActivate(next: ActivatedRoute,state: RouterStateSnapshot) {
        console.log(next)
        });
    }

The code snippet above shows that when we do a console.log(next), no data is seen in the 'next' object.

Answer №1

You can find the data within the ActivatedRoute object in the data property.

 checkActivation(next: ActivatedRoute, state: RouterStateSnapshot) {
        console.log(next.data);
    }

Answer №2

Make sure to include the data on the same level as the canActivate.

export const ContactRoutes: Route[] = [
    {
        path: '',
        component: ContactComponent,
        children: [
            { 
                path: '', 
                data: { id: '1', desc: 'foo' },
                canActivate: [canActivateService],
                component: DefaultComponent 
            },
        ]
    }
];

After that, access the data from the ActivatedRoute, as suggested by Ininiv.

canActivate(next: ActivatedRoute, state: RouterStateSnapshot) {
        console.log(next.data);
    }

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

Presenting data in various formats

I've got a JSON file with a list of data that includes months and years. I want to display all the months, but have the year only appear once in a big block area. Here's an image example: https://i.stack.imgur.com/Ps3OF.png The image demonstrates ...

Shift the Kid Element to an Alternate Holder

Currently, I am working on a project in Angular version 10. Within this app, there is a component that can be shared and will utilize the provided content through ng-content. Typically, this content will consist of a list of items such as divs or buttons. ...

Protecting Against Cross-Site Scripting Attacks in

I'm interested in implementing Angular, and I came across some information about its security measures. You can check it out here: https://angular.io/guide/security I want to clarify if just using Angular alone is sufficient to protect against all XSS ...

Is there a method to uncover the code that controls the display of a <div> element?

As a fresh face at the company, I've been given the responsibility of developing a chart that is similar to one already present on their website. While I have the knowledge and skills to create it, I am struggling to locate the specific code where the ...

extracting particular data from an Angular 6 observable

As I work with Angular 6, I have a scenario where I am making an API call using an interface. Here's how it looks: Service: getEmployees(): Observable<Employees[]> { return this.http.get<Employees[]>(this.getEmployeesAPI); } W ...

Exploring Angular14: A guide to efficiently looping through the controls of strictly typed FormGroups

Currently, I am working on upgrading my formGroups to be strictly typed in Angular v14. Within my FormGroup, there is a specific block of logic that iterates through all the controls and performs an action (this part is not crucial as I am facing issues be ...

Leverage ng2-charts along with a loading component during the AfterViewInit lifecycle hook

Currently, I am working on a web page that contains various charts. My focus right now is on developing a simple loader as shown below: <div *ngIf="loading === true; else elseBlock" class="container"> <div class="grid-pulse la-3x"> </di ...

Title: How to Build a Dynamic Logo Carousel with React and CSS without External Dependencies

Currently, I am in the process of integrating a logo carousel into my React web application using CSS. My goal is to create a slider that loops infinitely, with the last logo seamlessly transitioning to the first logo and continuing this cycle indefinitely ...

TypeScript is still verifying libraries in the node_modules directory despite skipLibCheck option being

I've been encountering an issue with TypeScript and React where TypeScript continues to check libraries in the node_modules folder even though I have "skipLibCheck" set to true in my tsconfig.json file. Below is a snippet of my tsconfig.json file, wh ...

Definitions for d3-cloud

I am trying to create a word cloud using d3-cloud in my Angular2 application. However, I am struggling to find the correct typings to install. I attempted to use this package @types/d3.cloud.layout from npm but encountered an issue when importing it into ...

Can anyone clarify what the term 'this' is referring to in this particular snippet of code?

Upon analyzing the following code snippet: export abstract class CustomError extends Error { abstract statusCode: number; constructor(message: string) { super(message); Object.setPrototypeOf(this, CustomError.prototype); } abstract seri ...

Jasmine was unsuccessful in detecting a exported function being invoked by another function

In my code, I've created 2 helper functions where one is a shortcut to the other. I need to verify in my test that the shortcut function is actually calling the main function. Both functions are located in the same file: export function test1(param1, ...

Is there a way to interrupt the routerLink function when a user is prompted in Angular 4+?

I am seeking to replicate the traditional functionality found in HTML where clicking a link triggers a confirmation pop-up before being redirected: <a href='http://www.example.com' onclick="if ( window.confirm ('Are you sure you want to ...

How to effectively handle null values using try..catch statement in typescript

As a beginner, I am learning how to write a try/catch statement in TypeScript. My issue is that there is a function within the "try" block that returns null. How can I implement code in the "catch" block specifically for when the function in "try" returns ...

Instructions for resolving the issue "Property 'focus' does not exist on type 'string'"

Struggling with an error message in my react typescript code: "Property 'focus' does not exist on type 'string'". Any help on resolving this issue would be appreciated. <!-- Let's start coding --> import { useRef, ...

Ending the connection in SignalR upon $destroy

I am currently working on a page that is utilizing SignalR, Angular, and Typescript. Upon the destruction of the current $scope (such as during a page change), I make an attempt to disconnect the client from the SignalR server: Controller.ts $scope.$on(&q ...

Modifying the functionality of "use-input" in Vue.js

Currently, I am utilizing vue.js along with typescript to create an input field that allows users to either choose items from a drop-down menu or manually type in their own input. There are various scenarios where custom input might be allowed or where onl ...

Converting hierarchical JSON data into a table with rowspan using Angular

I am facing a challenge in creating a table using nested JSON obtained from an API. I am unsure how to dynamically merge cells when needed, especially since the JSON structure can be nested up to 6 or 7 levels. Desired Table : Expected Table Current Ou ...

The function called within the XState machine cannot be invoked from within the class, yet it functions properly when defined as a

Is there a reason why I can't reference a method declared within the same class as XState service? It seems to work fine when the method is moved outside of the class. export class LoaderMachine { service = interpret(createMachine<LoaderContext ...

Send information to the main application component

Can data be passed two or more levels up from a Child Component to the App Component? https://i.stack.imgur.com/JMCBR.png ...