Angular 2 Routing and NgModule

a2

I’m in the process of updating the Angular 2 Three Stooges Tribute demo (that covered how to use the component router and implement your own Redux-style model) to the production release and a full-stack implementation.  The router is the same, although the setup is different in the app module.  The following screen shot illustrates the new setup (without lazy loading).

module

As you can see, it’s pretty easy to migrate the router setup to an app. module.

Another way to implement the same process is to separate routing concerns into a separate module and import that module into the main app module, i.e.

@NgModule({
  declarations: [
    ...lazyloadComponents,
    ...lazyloadDirectives,
    ...lazyloadPipes
  ],

  imports: [
    BrowserModule,
    AppRouteModule,
  ],

  providers: [],

  bootstrap: [AppComponent]
})

export class AppModule { }

And the AppRouteModule is defined as

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

// routable components
import { ScriptComponent    } from './script/script.component';
import { HistoryComponent   } from './history/history.component';
import { BioParentComponent } from './bios/bio-parent.component';
import { BioComponent       } from './bios/bio.component';
import { EpisodesComponent  } from './episodes/episodes.component';

@NgModule({
  imports: [
    RouterModule,
    RouterModule.forRoot([
    { path: ''        , redirectTo: 'script', pathMatch: 'full' },
    { path: 'script'  , component: ScriptComponent              },
    { path: 'bios'    , component: BioParentComponent           },
    { path: 'bios/:id', component: BioComponent                 },
    { path: 'history' , component: HistoryComponent             },
    { path: 'episodes', component: EpisodesComponent            }
    ]),
  ],

  exports: [RouterModule]
})

export class AppRouteModule { }

The next step is to lazy-load all routes other than the script, which corresponds to the home route.  I’ve already added UI elements to indicate that loading a new route for the first time is in progress.  CSS is in place to disable clicks on the main menu bar while a route is being loaded.  I will also add PHP services to return application data, and the demo will be setup to run live from the algorithmist.net domain.

Stay tuned.  More to come!

Comments are closed.