Routing in Angular 4 – Part 6

In this section, we will cover pending things of routing. Basically, in this section, we will cover Routing module and Route Guard.

Hence, without wasting time, let’s get started.

I have created one new module with the name app.routing-module.ts. Here, I have moved all my route related configurations. Its not necessary, but its good to have. It keeps App pretty neat and clean. Thumb rule is, if you have more than 2-3 routes, then you should isolate this in a separate file. Below, is the finished snippet for the same.

Let me explain the code a bit. Let’s start from bottom. Here, I have created a simple class which I am exporting because it needs to be imported at main module. Then, we have @NgModule with imports and exports section. Basically, in import section, I am setting up my route configuration and in export section I am mentioning that RouterModule, so that it can be available at app.module.ts. Other things are pretty simple, here we are just having different routes.  Now, let’s look at app.module.ts file. Below is the snippet for the same.

Here, first of all, file is become smaller and now it has only necessary stuffs to wire things up. One point to note here, that I imported my AppRoutingModule class here. With this change in place, nothing actually changes in application. It works the same way as before.

Demo project can be viewed at:

You can download code at:

Rahul Sahay,
Happy Coding