Angular 2 Routing and NgModule


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).


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.

  declarations: [

  imports: [

  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';

  imports: [
    { 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 domain.

Stay tuned.  More to come!

Comments are closed.