Retrieve the desired destination URL in the CanActivate guard when lazily loading modules in Angular

I am facing an issue with retrieving the target URL in the canActivate guard. Even though I have set up preloadingStrategy: PreloadAllModules in RouterModule.forRoot, the url property of ActivatedRoute does not contain the path. Here are the contents of both of my modules:

app.module.ts

const appRoutes: Routes = [
  { path: 'login', component: LoginComponent },
  {
    path: '',
    component: SiteLayoutComponent,
    children: [
      { path: '', redirectTo: 'dashboard', pathMatch: 'full' },
      {
        path: 'dashboard',
        loadChildren: './dashboard/dashboard.module#DashboardModule'
      },
      {
        path: 'user',
        loadChildren: './user/user.module#UserModule'
      }
    ]
  },
  { path: '**', component: PageNotFoundComponent }
];

@NgModule({
  declarations: [
    AppComponent,
    SiteLayoutComponent,
    LoginComponent,
    PageNotFoundComponent,
  ],
  imports: [
    RouterModule.forRoot(
      appRoutes,
      { enableTracing: false, preloadingStrategy: PreloadAllModules } 
    ),
    BrowserModule,
    BrowserAnimationsModule,
    HttpClientModule,
    HttpModule,
    FormsModule,
    CommonModule,
  ],
  providers: [AuthGuardAuthService, LoginService, SharedService],
  bootstrap: [AppComponent]
})
export class AppModule { }

user.module.ts

const appRoutes: Routes = [
    {
        path: 'user',
        children: [
            { path: '', redirectTo: 'create', pathMatch: 'full' },
            {
                path: 'create', component: CreateComponent, canActivate: [RouteGuard] //need activated route in this guard
            },
            { path: ':id/edit', component: CreateComponent },
            { path: 'list', component: UserListComponent }
        ],

    },
    {
        path: 'role',
        children: [
            { path: '', redirectTo: 'create', pathMatch: 'full' },
            {
                path: 'create', component: RoleComponent,
                resolve: {
                    Modules: RolesResolver
                }
            },
            {
                path: ':id/edit', component: RoleComponent,
                resolve: {
                    Modules: RolesResolver,
                }
            },
            { path: 'list', component: RoleListComponent },
        ],
    },
];

@NgModule({
    declarations: [
        CreateComponent,
        RoleComponent,
        UserListComponent,
        RoleListComponent
    ],
    imports: [
        CommonModule,
        FormsModule,
        RouterModule.forChild(
            appRoutes
        )
    ],
    providers: [RouteGuard, UserService, RoleService, RolesResolver],
})
export class UserModule { }

I require the activated route in RouteGuard.

Answer №1

verifyAccess(route: ActivatedRouteSnapshot, state: RouterStateSnapshot){
    console.log("route-access", state);
}

Referenced from this answer.

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

What could be causing the issue with my output not displaying correctly?

Hey guys! I'm working on creating a to-do list but I've encountered a problem. Whenever I enter a value in the text field, it doesn't get added to the array of list elements. Strangely enough, when I console.log it, it seems to work. Can any ...

Having trouble getting the header to properly sort the data retrieved from an Angular service?

I am currently working on implementing a simple table (date, weight) using Angular Material. The sorting functionality using "MatSort" is already set up and functioning well (you can view an example here). Now, I am attempting to retrieve data from an HT ...

Parallel Execution Issue with RxJS Observable forkJoin

Struggling to understand why my requests aren't executing concurrently with the following code. As a newcomer to RxJS and observables, I would greatly appreciate any guidance on improving this snippet below. Essentially, I am fetching data from a REST ...

What is the reason behind being able to assign unidentified properties to a literal object in TypeScript?

type ExpectedType = Array<{ name: number, gender?: string }> function go1(p: ExpectedType) { } function f() { const a = [{name: 1, age: 2}] go1(a) // no error shown go1([{name: 1, age: 2}]) // error displayed ...

Cypress and Cucumber synergy: Experience automatic page reloads in Cypress with each test scenario in the Describe block

Hey, I'm facing an unusual issue. I have a dialog window with a data-cy attribute added to it. In my cucumber scenarios, I have one like this: Scenario: Users open dialog window When the user clicks on the open dialog button I've written Cypre ...

Support for the percent sign in right-to-left languages

Imagine you have the following code snippet: <div dir="rtl"> test 50% </div> It currently displays as test 50%. However, according to this wiki page, for Arabic language it should be shown as %50 test, with the percentage sign before the n ...

Intellij2016 is issuing warnings for the sass use of the :host selector in Angular2 code

One interesting feature of Angular 2 is the special selector it uses to reference its own component: :host display: block height: 100% !important width: 100% text-align: center position: relative However, Intellij does not provide a way to supp ...

Guide on associating an array of object keys with an array of their corresponding values within a specified object

const obj = { wheels: 4, lights: 2, doors: 4 } customMapFunction(obj, { properties: ["wheels", "lights"], formatter: (wheels, lights) => `${wheels}-${lights}` // "4-2" }) How do I define the types for customMapFunction in TypeScript to ensure th ...

Finding Nested Key Paths in TypeScript for Objects and Arrays

I am in search of a unique method to create a TypeScript type that can take an object type and retrieve all the nested key paths, including properties within arrays as well. I want to exclude any default array properties such as "push" or "pop." While I ha ...

Angular 2 fails to apply active class colors to tabs in a modal popup

https://i.sstatic.net/T8lIu.pnghttps://i.sstatic.net/O21ZO.pngIn my modal popup, I have multiple tabs in the modal body. The issue I am facing is that when the modal is invoked, the active tab color is not being applied. The modal itself is built using ngx ...

Refreshing specific elements in Angular: A guide to selective change detection

Imagine I have a scenario where 100 divs are displayed on my screen through the *ngFor directive, pulling values from an object structured as follows: {A1: someObject, A2: someOtherObject..., J10: someOtherOtherObject} Upon clicking on A1 and then on J10 ...

Understanding the tsconfig.json file in an Angular project

I encountered the following error in my tsconfig.ts file: 'No inputs were found in config file 'c:/Projects/Angular2//src/tsconfig.json'. Specified 'include' paths were '["src/**/*.ts"]' and 'exclude' paths ...

Issue with unit testing a ViewportRuler in Angular 2 Material Library

I am currently working on an Angular2 component that includes a tab control from @angular/material. During testing of my component (refer to the simplified code below), I encountered the following error: Error: Error in ./MdTabHeader class MdTabHeader - ...

Using the useStaticQuery hook outside of a function component is not allowed and will result in an invalid hook call error. Remember to only call

I am currently facing an issue while trying to retrieve values using useStaticQuery from my gatsby-config.js file. Below are snippets of my code. Does anyone have any suggestions on how to resolve this problem? Thank you in advance. Repository: https: ...

Unable to locate the name 'Cheerio' in the @types/enzyme/index.d.t file

When I try to run my Node application, I encounter the following error: C:/Me/MyApp/node_modules/@types/enzyme/index.d.ts (351,15): Cannot find name 'Cheerio'. I found a suggestion in a forum that recommends using cheerio instead of Cheerio. H ...

What is the process of mapping an array of elements for a React component using TypeScript?

Check out my unique component: import React, { FunctionComponent as FC } from 'react'; type shapeMidNumbersInput = { arrMidNumbers: Array<number> }; const MidNumbers: FC<shapeMidNumbersInput> = ({ arrMidNumbers }): Array<Element ...

Unable to redirect to another page in React after 3 seconds, the function is not functioning as intended

const homeFunction = () => { const [redirect, setRedirect] = useState<boolean>(false); const [redirecting, setRedirecting] = useState<boolean>(false); const userContext = useContext(UserContext); useEffect(() => { const valu ...

Leveraging NestJs Libraries within Your Nx Monorepo Main Application

I am currently part of a collaborative Nx monorepo workspace. The setup of the workspace looks something like this: https://i.stack.imgur.com/zenPw.png Within the structure, the api functions as a NestJS application while the data-access-scripts-execute ...

Delivering secure route information to paths in Angular 2

When defining my routes in the routing module, I have structured the data passing like this: const routes: Routes = [ { path: '', redirectTo: 'login', pathMatch: 'full' }, { path: 'login', component: LoginCompon ...

Typescript: searching for a specific type within an array of objects

The title may be a bit unclear, but I'm struggling to find a better way to explain it. I have a predefined set of classes from a third-party library that I cannot modify. The specific content of these classes is not relevant, as it's just for i ...