Utilizing Angular 8's lazy loading feature for routes, we can resolve routes both with and without a

I have been experimenting with the router and lazy loading in Angular 8, having previously used it successfully in Angular 7.
I have set up some basic routes as shown below:

/home
/auth
/auth/login
/auth/signUp

My goal is to redirect /auth to /auth/login and everything else to /home.
To achieve this, my app-routing.module.ts file looks like this:

const routes: Routes = [
  {
    path: '',
    redirectTo: '/home',
    pathMatch: 'full'
  },
  {
    path: 'auth',
    loadChildren: () => import('./modules/auth/auth.module').then(m => m.AuthModule)
  },
  {
    path: 'home',
    loadChildren: () => import('./modules/home/home.module').then(m => m.HomeModule)
  },
  {
    path: '**',
    redirectTo: '/home',
    pathMatch: 'full'
  }
];

My auth-routing.module.ts file looks like this:

const routes: Routes = [
  {
    path: '',
    redirectTo: '/auth/login',
    pathMatch: 'full'
  },
  {
    path: 'login',
    component: LoginComponent
  },
  {
    path: 'signUp',
    component: LogoutComponent
  }
];

The issue I am facing is that it always redirects to the auth page and disregards the other redirects. The paths /login and /signUp are also accessible at a root level, which seems strange, but they still work when prefixed with /auth/login, which adds to the confusion.

It appears that the routes are somehow duplicated.
Furthermore, when I prefix the paths in auth-routing.module.ts with auth/, it becomes possible to navigate to /auth/auth/login.

I have enabled all necessary features of Angular 8 for Ivy and lazy loading to function properly. The remaining routes and lazy-loaded modules I defined are functioning correctly.

Answer №1

To implement relative redirects, you can follow this format:

In app-routing.module.ts:

import {NgModule} from '@angular/core';
import {Route, RouterModule} from '@angular/router';
const routes: Route[] = [
  {
    path: '',
    redirectTo: 'home',
    pathMatch: 'full'
  },
  {
    path: 'auth',
    loadChildren: () => import('./modules/auth/auth.module').then(m => m.AuthModule)
  },
  {
    path: 'home',
    loadChildren: () => import('./modules/home/home.module').then(m => m.HomeModule)
  },
  {
    path: '**',
    redirectTo: 'home',
    pathMatch: 'full'
  }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule {
}

In auth-routing.module.ts:

import {NgModule} from '@angular/core';
import {Route, RouterModule} from '@angular/router';
import { LoginComponent } from './login.component';

import { LogoutComponent } from './logout.component';
const routes: Route[] = [
  {
    path: '',
    redirectTo: 'login',
    pathMatch: 'full'
  },
  {
    path: 'login',
    component: LoginComponent
  },
  {
    path: 'signUp',
    component: LogoutComponent
  }
];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule]
})
export class AuthRoutingModule {
}

In home-routing.module.ts:

import {NgModule} from '@angular/core';
import {Route, RouterModule} from '@angular/router';
import { HomeComponent } from './home.component';
const routes: Route[] = [
  {
    path: '',
    component: HomeComponent
  }
];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule]
})
export class HomeRoutingModule {
}

For a demo, check out https://stackblitz.com/edit/angular-gmsgn2.

Answer №2

To successfully implement lazy loading in your Angular project, ensure that you import AuthModule and HomeModule exclusively in the app-routing.module.ts. Double-check to make sure these modules are not mistakenly imported in the app.module.ts file using the traditional non-lazy loading method.

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

Does anyone have experience using the useRef hook in React?

Can someone help me with this recurring issue: "Property 'value' does not exist on type 'never'" interface InputProps { name: string; icon?: ReactElement; placeholder?: string; } const Input = ({ name, icon: Icon, ...rest }: Inpu ...

Tips for categorizing items based on their names

Upon receiving a response as shown below: [ {id:1,name:"type1-something"}, {id:2,name:"something-type2"}, {id:3,name:"type3-something"}, {id:4,name:"something-type1"} ] I have an Enum with ...

The default route in Angular 2 is failing to function correctly

Within my routing.module.ts file, I have the following code snippet: const routes: Routes = [ { path: '', redirectTo: 'Home', pathMatch: 'full' }, { path: 'Home', component: HomeComponent }, { path: &a ...

After reinstalling all components, the system does not recognize 'ng'

After encountering numerous issues with the latest version of node.js, I decided to start fresh by uninstalling everything. I removed the angular/CLI and uninstalled npm using the command npm uninstall -g npm. I then deleted the npm file and uninstalled no ...

Guide on posting an object in Angular through HTTP Post

I am attempting to send an object named Pack to my API Rest server using my Angular service. Below is the function I have set up for this task: save_pack(Pack: any){ return new Promise((resolve, reject) =>{ this.http .post("http://loca ...

AngularFireFunctions httpCallable doesn't reflect updated data post-response

Despite successfully receiving a value from an Observable using AngularFireFunctions' httpsCallable, the view fails to update even after the http request is completed. In my simple component, I utilize AngularFireFunctions to invoke an httpCallable f ...

Identifying alterations in material table data source caused by functional techniques

How come mutating the material table data source with functional methods like splice does not trigger any changes to the render? Unlike the assignment operator, which results in directly rendering new mutated data. I attempted to use a change detector aft ...

Adjusting the vertical dimension of an Angular 17 Material Dropdown Field?

Check out this demo where I'm exploring ways to decrease the height of the select field. Here's the code snippet: <mat-form-field appearance="outline"> <mat-label>Toppings</mat-label> <mat-select [formControl]=& ...

How to calculate the sum of all values in a FormArray in Angular

I am trying to retrieve the input values from each row and then calculate the sum of these rows. Here is my HTML code: <ng-container formArrayName="cap_values"> <tbody *ngFor="let item of capValues.controls; let i=index" [formGroupName]="i"& ...

updating the observable array in rxjs after every iteration

I am facing an issue with updating the status of contracts in my UI. I have an Observable that contains an array of ContractDto, which is displayed in a table using an async pipe. The 'status' column for each contract initially shows 'not pr ...

gulp-webpack is unable to locate node packages

Currently working on developing a modern Angular application. I have opted to use gulp-webpack for quick development builds. To handle my TypeScript bundling and node modules dependencies, I am relying on webpack. However, it seems that gulp-webpack is no ...

Exploring i18next language settings with Typescript

I wrote a function that retrieves locale information like this: fetchLocale.ts import i18next from 'i18next'; export const fetchLocale = (locale) => { return i18next.t('value', { locale }) } Additionally, here is the test I create ...

Creating an image using the @aws-sdk/client-bedrock-runtime package is a simple process

Having crafted a BedrockRuntimeClient using typescript, I'm stumped on how to call upon the model and execute the command. const client = new BedrockRuntimeClient({ region: "us-east-1", apiVersion: '2023-09-30', ...

A Promise signature allows for the compilation of function bodies that return undefined

The compiler error that I expected to see when using this function does not actually occur. The function body is capable of returning undefined, yet the type signature does not mention this possibility. async function chat(_: at.ChatLine): Promise<Arr ...

Having trouble with Ionic on Safari and iOS 11 when using the ServiceStack Client

My Ionic app is encountering issues when calling any webservice method (ServiceStack) on Safari 11.1 (13605.1.33.1.2). The same problem occurs when running on iOS 11 device or simulator, as shown in the attached image. The app functions properly on Chrome ...

What is the best way to send a ref from forwardRef to a specialized hook in TypeScript?

I'm currently working on implementing the useIntersection hook in my code. Everything seems to be functioning correctly, but I've run into some issues with TypeScript: import { MutableRefObject, useEffect } from 'react'; export default ...

I'm really puzzled as to why they would choose to export in this manner in React

I noticed that several files were exported in a similar manner, and I'm unsure why this specific method was chosen. Could there be any advantages or particular reasons for exporting them like this? index.ts export { default } from './Something& ...

Developing a dynamic object in Typescript to structure and optimize API responses

Currently Working Explanation: This is similar to the data array received from the API response responseBarDataStacked = [ { sku: "Data 1", month: "Jun", value: 20 }, { sku: "Data 2", month: "Jun", value: 25 ...

Failed to hit breakpoint in TypeScript file while working with Visual Studio 2019 and Webpack

We are working on an ASP.NET MVC 5 application where we are incorporating TypeScript for client-side code and using webpack to bundle everything into a single js file. TypeScript has been installed via npm. However, we have encountered an issue where setti ...

Exploring the Vue 3 Composition API with TypeScript and Working with Object Keys

Exploring the Vue-3 composition API and seeking guidance on utilizing types with TypeScript in Vue. Looking for more detailed information on how to define object properties and specify keys in TypeScript within the composition API, as the current document ...