Organize routes into distinct modules in Angular 6

Currently grappling with routing in my Angular 6 application. Wondering if the structure I have in mind is feasible. Here's what it looks like:

The App module contains the main routing with a parent route defining the layout:

const routes: Routes = [
{
    path: 'login',
    component: LoginComponent
},
{
    path: '',
    component: LayoutComponent,
    canActivate: [AuthGuard],
    canActivateChild: [AuthGuard],
    children: [
    // {
    //   path: 'brands',
    //   loadChildren: 'app/modules/brands/brands.module#BrandsModule',
    //   pathMatch: 'prefix'
    // }
    ]
}
];

@NgModule({
    imports: [RouterModule.forRoot(routes), BrandsModule, ItemsModule],
    exports: [RouterModule],
    providers: [BosRouteLoader]
})
export class RoutingModule {}

A feature module defines its own routing module like this:

const routes: Routes = [
{
    path: 'brands',
    children: [
    { path: '', component: BrandListComponent },
    { path: ':id', component: BrandDetailComponent },
    { path: '**', redirectTo: '' }
    ]
}];


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

My goal is to have each feature module define its own routing and register those routes as child routes of the App module.

Leveraging lazy loading works, but requires me to always define an additional route in the App module, which I prefer not to do. If I avoid lazy loading, the parent route in the App component is never reached. So when navigating to http://localhost/brands, it loads the BrandListComponent without the LayoutComponent.

Is there a way to define routes in feature modules and register them as children of the main routing module?

Answer №1

The idea is to set up a module routing within your main module and then specify its child routes in the respective modules.

In your scenario, you need to instruct Angular that when someone navigates to the brands route, they should utilize the routes defined in the BrandsRoutingModule.

In your app module, this configuration will look like:

{
    path: 'brands',
    loadChildren: 'app/modules/brands/brands.module#BrandsModule',
    canActivate: [AuthGuard],
    canActivateChild: [AuthGuard],
}

This indicates that the module's routing should be loaded when the user visits /brands.

Next, in your BrandsRoutingModule, define the routes as follows:

{
    path: '',
    component: LayoutComponent,
    children: [
        { path: '', redirectTo: 'home', pathMatch: 'full' },
        { path: 'home', component: BrandListComponent },
        { path: ':id', component: BrandDetailComponent },
        { path: '**', redirectTo: '' }
    ]
}

When navigating to /brands, the main view will be LayoutComponent, with BrandListComponent and others nested within as child components. To display these child elements, add the following line of code in your layout.component.html:

<router-outlet></router-outlet>

This informs Angular that if navigating to, for example, /brands/2, the BrandDetailComponent should be loaded within the LayoutComponent, essentially serving as its child component.

I trust this explanation clarifies things for you.

Answer №2

JohnDoe123's solution is great for handling lazy loaded modules, especially since the traditional method of using LoadChildren is now considered deprecated. On the other hand, when it comes to eagerly loaded modules, a different strategy can be employed to organize the main routes module and distribute them across multiple modules:

MainRoutingModule.ts

const MODULE_ROUTES = [...module1Routes, module2Routes];

const routes: Routes = [

  { path: 'path1', component: Path1Component },
  { path: 'path2', component: Path2Component },
  ...MODULE_ROUTES,
];

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

Rather than listing all child routes within the main routing file, each feature module can have its own *.route.ts file where routes are declared and exported in a cleaner manner. Here's an example of how this can be implemented:

export const module1Routes: Routes = [
{
    path: 'brands',
    children: [
        { path: '', component: BrandListComponent },
        { path: ':id', component: BrandDetailComponent },
        { path: '**', redirectTo: '' }
    ]
}];

By importing these individual route files into the main routing file, Angular can seamlessly access them as needed.

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

Struggling with getting render props to work in Next.js version 13

Looking to develop a custom component for Contentful's next 13 live preview feature in the app directory, I thought of creating a client component that can accept a data prop and ensure type safety by allowing a generic type to be passed down. Here is ...

Is it possible to create a personalized serialize form when sending an AJAX POST request

How can I format form data on an AJAX POST request differently than the default $("#formid").serialze()? The current result is not suitable for my needs, as it looks like this: `poststring="csrfmiddlewaretoken=bb9SOkN756QSgTbdJYDTvIz7KYtAdZ4A&colname= ...

Material-UI is having trouble resolving the module '@material-ui/core/styles/createMuiTheme'

Although I have searched for similar issues on StackOverflow, none of the solutions seem to work for me. The errors I am encountering are unique and so are the fixes required, hence I decided to create a new post. The company conducting my test provided m ...

The issue of underscorejs being undefined arises when trying to load it using both XMLHttpRequest and

I am attempting to dynamically load underscorejs using XMLHttpRequest and eval function function includeScriptSync(scriptUrl) { var xmlhttp = new XMLHttpRequest(); xmlhttp.open("GET", scriptUrl, false); xmlhttp.onreadystatechange = function() ...

Having trouble getting the map function to work in ReactJs while using Next.js?

Hey there, I am diving into ReactJS with the "Nextjs" framework and working on fetching data using async functions. However, I am facing an issue where I am unable to fetch data using the map function. The console.log is displaying a message saying "item ...

Struggling to properly implement background images in a React application using Tailwind CSS

I'm currently developing a React application using Tailwind CSS for styling. In my project, I have an array of items called "trending," and I'm attempting to iterate through them to generate a series of divs with background images. However, I am ...

The file functions/lib/functions/src/index.ts is missing, preventing the deployment of Cloud Functions

Whenever I attempt to deploy my Firebase cloud functions, I encounter the following error. Expected outcome: Successful deployment of functions. Error: Error: An issue occurred while reading functions/package.json: functions/lib/index.js is missing and ...

Resetting the quiz by utilizing the reset button

Hello everyone, I'm new to this platform called Stack Overflow. I need some help with my quiz reset button. It doesn't seem to be working as intended. According to my code, when the reset button is clicked at the end of the quiz, it should bring ...

What could be causing my date variable to reset unexpectedly within my map function?

Currently, I'm utilizing a tutorial to create a custom JavaScript calendar and integrating it into a React project You can find the functional JavaScript version in this jsfiddle import { useState, useRef, useMemo } from 'react' import type ...

Is there a way to alter the format of a URL?

I'm utilizing the ytdl-core library to access a URL for audio content. The provided URL is: https://r2---sn-gwpa-w5py.googlevideo.com/videoplayback?expire=1612552132&ei=ZEMdYNnJDumPz7sPyrSLmAw&ip=49.36.246.217&id=o-AFQLS1cSUJ6_bXBjMOIiWk1N ...

Node.js JSON parser encountering an unexpected undefined error

Whenever I attempt to JSON.parse the string, an error occurs and I receive this message: undefined:1 {"device":"FaclonTest","data":[{"tag":"LATITUDE","value":1903.5091},{"tag":"LONGITUDE","value":07251.0348}]} I'm unsure of where the mistake is. Can ...

Learn how to update image and text styles using Ajax in Ruby on Rails with the like button feature

I'm working on implementing a Like button in Rails using Ajax, similar to this example: Like button Ajax in Ruby on Rails The example above works perfectly, but I'm interested in incorporating images and iconic text (such as fontawesome) instead ...

Navigating with Angular: Every time I refresh the page or enter a specific URL, Angular automatically redirects to the parent route

In my CRM module, I have created a custom Routing Module like this: const routes: Routes = [ { path: 'crm', component: CrmComponent, children: [ { path: '', redirectTo: 'companies', pathMatch: 'full&ap ...

Troubleshooting compatibility issues between Sailsjs Services and TypeScript in Vscode

Having an issue with TypeScript in a Sails.js application. I am utilizing TypeScript to write my controller and attempting to use Sails.js services within the controllers. However, I encounter a syntax error in VSCODE. Below is the code snippet from MyCo ...

Acquire multiple instances of NestJs dependencies using dependency injection within a single class

Below is a class called Product @Injectable() export class Product { brand: string; } I am injecting the Product class into ProductService export class ProductService { constructor(private readonly product: Product) {} update(products) { ...

Issue with preventdefault() function in Internet Explorer 8

I've encountered a problem while working on a page that heavily utilizes ajax. Everything seems to be functioning well across different browsers, except for one final step that is broken in IE8 and below. You can view the issue on this demo page: To ...

Angular component failing to refresh data upon service response

Within my Angular component, I have integrated badges onto certain icons. These badge numbers are fetched from an api upon entering the page, utilizing ionViewWillEnter(). Once the api response is received, the outcome is stored in a local variable, which ...

Troubleshooting issue: Click function not responding inside Bootstrap modal

Below is the JavaScript code for my click function $(".addPizza").on("click", function(event) { event.preventDefault(); console.log("hello") let userId = $("#userId").attr("data-id"); let pizzaRecipe = $('#pizza-recipe').val().trim(); ...

How can I manually listen to Angular 2 events on a dependency injected instance?

Assume I am working with a component: @Component({selector: 'todo-cmp'}) class TodoCmp { @Input() model; @Output() complete = new EventEmitter(); // TypeScript supports initializing fields onCompletedButton() { this.complete.next(); / ...

Angular: Eliminating code duplication through service transfer

One code snippet that I frequently use when booting the app is (ngOnInit): this.route.queryParamMap.subscribe( params => { const id = params.get('id'); if (id) { this.contactsService.GetContactByUserId(id) .subscribe( ...