Angular : Couldn't find a route declaration in /src/app/app-routing.module.ts

Viewed 3830

When I try to add automatic routing for components generated using following command

ng generate module orders --route orders --module app.module

I get the error

Couldn't find a route declaration in /src/app/app-routing.module.ts.

app-routing.module.ts

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


@NgModule({
  declarations: [],
  imports: [
    CommonModule
  ]
})
export class AppRoutingModule {

 }

I also tried adding this line the app-routing file

export const routes: Routes = []

Still problem persits.How to fix this error?

5 Answers

I faced the same problem when was using angular template. Solution was to write routing file name explicitly

ng generate module customers --route customers --module app.routing.ts

Try to use command ng generate module orders --route orders --module app-routing.module, as described in cli module documentation :

--route The route path for a lazy-loaded module. When supplied, creates a component in the new module, and adds the route to that component in the Routes array declared in the module provided in the --module option.

Looks like tutorial cli command (ng generate module customers --route customers --module app.module) works fine only while your file structure is close to default and it can easily find routes array.

You need to add the routes to your Angular Module (@NgModule). Follows an example how to do it (more info here):

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';

// Import the RouterModule
import { Routes, RouterModule } from '@angular/router';

//import the routes from your app-routing file
import { routes } from './app-routing';

@NgModule({
  declarations: [],
  imports: [
    CommonModule,

    //Add the routes to your Angular Module
    RouterModule.forRoot(routes)
  ]
})
export class AppRoutingModule {

 }

Run this command ng generate module app-routing --flat --module=app to create app-routing.module.ts file then add the code const routes: Routes = []; like this

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


const routes: Routes = [];
@NgModule({
  declarations: [],
  imports: [
    CommonModule, RouterModule.forRoot(routes)
  ],
  exports: [RouterModule]
})

export class AppRoutingModule { }

after that you can run your command

it worked for me:

first create my module by this code :

ng g module orders --routing

after that, I declare my component in my-module

Related