alim1990
alim1990

Reputation: 4972

Angular 2 Child route module display the correct url but displays another component

I cleaned up my root route file, by creating a child custom module for routes, and here is the script:

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { SigninComponent } from './signin/signin.component';
import { SignupComponent } from './signup/signup.component';

const childRoutes: Routes = [

    {path: 'signin', component: SigninComponent},

    {path: 'signup', component: SignupComponent}

];

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

The root route module now is:

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { SigninComponent } from './auth/signin/signin.component';
import { SignupComponent } from './auth/signup/signup.component';
import { NotfoundComponent } from './notfound/notfound.component';
import { ChildRoutingModule } from './auth/auth.route'

const appRoutes: Routes = [
    {path: '', redirectTo:'/signup', pathMatch:'full'},

    {path: '**', component: NotfoundComponent}
];

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

I imported the 2 route modules into the app.module.ts:

import ...
import ...
import { AppRoutingModule } from './routes'
import { ChildRoutingModule } from './auth/auth.route'
@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    AppRoutingModule,
    ChildRoutingModule,
    BrowserModule,
    AuthModule,
    RouterModule 
  ],
  providers: [AuthService],
  bootstrap: [AppComponent]
})
export class AppModule { }

The problem now is on the startup component of the app that is the signup component, the url is correct: http://localhost:4200/signup but the displayed component is the 404 component which is defined in the root route component by {path: '**', component: NotfoundComponent}

To mention that no errors are displayed at the console at all

Upvotes: 0

Views: 591

Answers (2)

Vivek Doshi
Vivek Doshi

Reputation: 58593

Change this as:

imports: [
    BrowserModule,
    AuthModule,
    RouterModule,
    ChildRoutingModule, 
    AppRoutingModule,
  ],

You need to load AppRoutingModule at last , because before that route routes needs to know all the child routes , to make routing deep level on init time.

Or it will redirect to the Error Component as you have defined.

Upvotes: 1

fredrik
fredrik

Reputation: 17617

You need to import AppRoutingModule last. https://angular.io/docs/ts/latest/guide/router.html#!#routing-module-order

Upvotes: 2

Related Questions