Error in Angular 2 Router: Consistently redirecting to the homepage

I have recently created an Angular 5 application and have been debugging it without encountering any compile errors. Everything was working fine initially when I only used one route.ts file and one app.module.ts file for the entire project. However, as the project started to grow, I realized that maintaining this structure would become more complex. This led me to restructure my folders, but now every time I navigate to other URLs, it redirects me back to the home page.

In terms of my new folder structure, I have created separate app modules and route modules for each specific function. The home page and login page are designed with different layouts. For example, the authentication routes are handled by auth-routing.module.ts which is then imported into auth.module.ts. Similarly, I have an app-routing.module.ts to manage the main routes, which in turn is imported into app.module.ts.

Here's a glimpse of my folder structure:

https://i.sstatic.net/YXRVD.png

auth-routing.modules.ts

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterModule, Routes } from '@angular/router';

import { NoAuthGuard } from '../auth/no-auth-guard.service';
import { HomeAuthResolver } from '../layout/home-auth-resolver.service';

import { AuthComponent } from '../auth/components/index';

const routes: Routes = [  
    { path: 'login', component: AuthComponent},
    { path: 'register', component: AuthComponent }       
];

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

auth.module.ts

import { ModuleWithProviders, NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { RouterModule } from '@angular/router';

import { AuthRoutingModule } from './auth-routing.module';
import { AuthComponent} from './components/index';

@NgModule({
  declarations: [     
    AuthComponent          
  ],
  imports: [
    BrowserModule,    
    AuthRoutingModule   
  ],
  providers: [ ]     
})
export class AuthModule { }

app-routing.module.ts

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterModule, Routes } from '@angular/router';

import { NoAuthGuard } from './auth/no-auth-guard.service';
import { HomeAuthResolver } from './layout/home-auth-resolver.service';

import {LayoutComponent,  PUBLIC_ROUTES } from './layout/index';

const routes: Routes = [ 
    { path: '', component: LayoutComponent, data: { title: 'Secure Views' }, children: PUBLIC_ROUTES },
    { path: '**', component: LayoutComponent, data: { title: 'Secure Views' }, children: PUBLIC_ROUTES }
];

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

app.module.ts

import { ModuleWithProviders, NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { RouterModule } from '@angular/router';

//modules
import { AppRoutingModule } from './app-routing.module';
import { AuthModule } from './auth/auth.module';

// Layouts
import { AppComponent } from './app.component';
import { LayoutComponent, HomeAuthResolver } from './layout/index';

//child components
import { HomeComponent } from './home/home.component';

//shared components
import { ApiService, AuthGuard, FooterComponent, HeaderComponent } from './shared';


@NgModule({
  declarations: [
    AppComponent,
    FooterComponent,
    HeaderComponent,
    LayoutComponent,
    HomeComponent,

  ],
  imports: [
    BrowserModule,
    AppRoutingModule,   
    AuthModule
  ],
  providers: [
    ApiService,
    AuthGuard,
    HomeAuthResolver,
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

Answer №1

Make sure you have not forgotten to export AuthRoutingModule in your auth.module.ts file.

Here is the corrected code for auth.module.ts:

import { ModuleWithProviders, NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { RouterModule } from '@angular/router';

import { AuthRoutingModule } from './auth-routing.module';
import { AuthComponent} from './components/index';

@NgModule({
  declarations: [     
    AuthComponent          
  ],
  imports: [
    BrowserModule,    
    AuthRoutingModule   
  ],
  exports: [AuthRoutingModule],
  providers: [ ]     
})
export class AuthModule { }

Also, remember to remove the usage of CommonModule in your auth-routing.module.ts as shown below:

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';

import { NoAuthGuard } from './auth/no-auth-guard.service';
import { HomeAuthResolver } from './layout/home-auth-resolver.service';

import {LayoutComponent,  PUBLIC_ROUTES } from './layout/index';

const routes: Routes = [ 
    { path: '', component: LayoutComponent, data: { title: 'Secure Views' }, children: PUBLIC_ROUTES },
    { path: '**', component: LayoutComponent, data: { title: 'Secure Views' }, children: PUBLIC_ROUTES }
];

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

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 Service worker mishandles http redirects (302)

In my current project, I am implementing Angular and Spring Boot technologies. When I build the project, Angular generates the service worker for me. The issue arises when I use an external service (auth2) and my backend redirects to the login page after ...

"Embracing the power of multiple inheritance with Types

I am struggling with the concept of multiple inheritance in TypeScript. It doesn't make sense to overload a hierarchy with too much functionality. I have a base class and several branches in the hierarchy. However, I need to utilize mixins to isolate ...

The message shown on items.map stating that parameter 'item' is implicitly assigned the type 'any'

Currently, I am delving into the world of Ionic React with Typescript by developing a basic app for personal use. My current challenge involves dynamically populating an IonSegment from an array. Here is the relevant code snippet: const [items, setItems] ...

Using Node.js and Typescript to bring in external modules from

Attempting to generate a random integer between 1 and 6 using the 'random' library. Here's what I have coded so far: import random from 'random' function rollDice(min:number, max:number) { return Math.floor(Math.random() * (ma ...

The inRequestScope feature seems to be malfunctioning and is not functioning as intended

Need help with using inRequestScope in inversifyJS For example: container.bind<ITransactionManager>(Types.MysqlTransactionManager).to(MysqlTransactionManager).inRequestScope() ... container.get<ITransactionManager>(Types.MysqlTransactionMana ...

The browser does not store cookies in its memory

After conducting extensive research on this issue, I have not been able to find a solution yet. In essence, I am currently running a Node.js API server on localhost:3000 and an Angular 10 app on localhost:4200. The problem is straightforward - when I make ...

Display PDF in Forge Viewer using PDF Extension - warning generated by pdf.worker.js

Whenever we attempt to display a PDF file using our own API, the pdf.worker.js generates a warning message and the PDF always appears completely white. https://i.stack.imgur.com/IqGML.png All I can see is this (it's a wide PDF that renders fine in t ...

A guide on dynamically displaying Primeng Components within Angular applications

My task involves dynamically rendering Primeng components along with regular HTML elements. The template for rendering is stored as a string, as shown below: const dynamicTemplate = `<div class="card flex flex-row gap-3 justify-content-cen ...

Can someone guide me on finding my staticwebapp.config.json within Azure Devops for deploying Azure Static Web Apps during a release?

After setting up a pipeline to build the artifact for my Angular application, I encountered an issue with deployment where specific URLs would redirect me to a 404 error page. This problem seems to be related to the configuration in staticwebapp.config.jso ...

JavaScript Tutorial: Adding Custom Metadata to PDFs

Does anyone know of a JavaScript package that can assist in adding custom metadata to a PDF file? ...

Connect your Angular2 app to the global node modules folder using this link

Is there a way to set up a centralized Node modules folder on the C disk instead of having it locally within the app directory? This would be more convenient as Angular2 CLI tends to install over 125mb of Node modules in the local folder. In our TypeScrip ...

Tips for enhancing the TypeScript definition of Material UI 3 theme by integrating the Material UI pickers theme

Trying to enhance the Material-UI theme with the Typescript typings of Material-UI-Pickers for the latest versions listed here: "@material-ui/core": "^3.9.2", "material-ui-pickers": "^2.2.1", A note on the bottom of the Material UI picker page mentions t ...

Generic Typescript abstract method error: "the class specifies the property as an instance member, but the extended class defines it as an instance member function."

Upon exploring the code in this playground link, abstract class Base<F extends () => void> { public abstract __call__: F; } type CallSignature<T> = { (): T; (value: T): void; } class Foo<T> extends Base<CallSignature&l ...

Locate a specific element within a multi-dimensional array based on a partial match of one of its properties with a provided text

I am working with an array that includes three properties: ID : number Name : string Description :string ItemList :array<T>=[] and ItemListCopy :array<T>=[] Currently, this array is linked to the ng-multiselect dropdown During the onFilt ...

Dealing with custom path problems in Angular 2+ webpack configurations

I am interested in using the @ngneat/tailwind schematics to convert an Angular project into one with a custom webpack configuration. However, after adding this, my scss import paths for fonts and other partial scss files are not resolving, resulting in th ...

What is the process for incorporating an external file into Angular CLI?

I have a project where I am trying to extract element details from an HTML file using the Angular CLI. However, I encountered an error while using PHP to fetch the file content: ./bodycontent/load.php file not found... zone.js:2933. Does anyone know how ...

Adjust the properties within the component's styles using Angular 2

In this project, the objective is to dynamically change the background-color based on different routes. The goal is to display a specific color for UpcomingComponent while keeping the background-color consistent for all other routes. The approach involves ...

Issue with NgRx Testing: Callback in subscribe method fails to update during testing

I am currently working on testing a component that is responsible for editing shopping list items. Upon first loading, the component receives state values through store.select, which are: editedIngredient: null, editedIngredientIndex: -1 Based on these ...

Learn how to easily set a radio button using Angular 4 and JavaScript

It seems like a simple task, but I am looking for a solution without using jQuery. I have the Id of a specific radio button control that I need to set. I tried the following code: let radiobutton = document.getElementById("Standard"); radiobutton.checke ...

What is the best way to showcase development using an Angular bar graph?

Does anyone have any suggestions on how to create a visualization like the one shown in this mockup? https://i.stack.imgur.com/X72RP.png The mockup features two bar charts, each with a greyed-out area representing its own 100% or max value. For simplicity ...