Build Your First Angular Website: Lazy Loading an Angular Section

Publikováno: 30.8.2018

Next up, let's create a section of our site specifically dedicated to users. We have many users that are part of our site and we'll have two parts to this:

  • /users where we ...

Celý článek

Next up, let's create a section of our site specifically dedicated to users. We have many users that are part of our site and we'll have two parts to this:

  • /users where we can browse and see all users
  • /users/username where we can see a specific user's profile

Since this section of our site might not always be visited, it makes sense that we only load these components if a user visits one of these sections.

Organizing with NgModule

This is where the NgModule comes in. We can separate the parts of our site into these modules that have grouped set of functionality. We'll create a new module for our users section. Use the Angular CLI to handle the generation for us:

ng g module users --routing

Now we have this new folder for users/users.module.ts. We can see our UsersModule also:

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

import { UsersRoutingModule } from './users-routing.module';

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

Notice that this NgModule already includes the router for this /users section. This is great because each module can be responsible for its own routing. The main AppRoutingModule will grab all the routers from across our app and build out all the routes.

Generating User Components

Now that we have the UsersModule for this section of our site, we can add two components for the users page and users/username page. You can name these whatever makes sense to you; I'll be going with Users and UserSingle

# component to show all users
ng g component users/user-list

# component to show a single user
ng g component users/user-single

Notice that we are doing a couple important things:

  • Nesting these underneath the users/ prefix. This makes sure Angular adds these components to the UsersModule.
  • Dash-naming for our components. Angular will turn user-single into UserSingleComponent

Now we can see our UsersModule has these two components added in the declarations property:

@NgModule({
  imports: [
    CommonModule,
    UsersRoutingModule
  ],
  declarations: [UsersComponent, UserSingleComponent]
})
export class UsersModule { }

Adding Users Routing

Now that we have our module and components made, we need to update our users-routing.module.ts so that our users section knows what its own routes are.

// src/app/users/users-routing.module.ts
// ...
import { UserListComponent } from './users/user-list.component';
import { UserSingleComponent } from './user-single/user-single.component';

const routes: Routes = [
  {
    path: '',
    component: UserListComponent
  },
  {
    path: ':username',
    component: UserSingleComponent
  }
];

We've added our two routes to the routes array. Like all things ES6, we also imported our components so that this file knows where to get them. We didn't add /users to the path strings because that will be handled from our parent router. The parent router will say "for all /users routes, use the UsersRoutingModule. We'll see this in action in the next lesson.

Route Parameters in Routes

To declare a route parameter in your routes, just use the : before your variable name. Angular will take whatever is in that spot in the url and turn it into a route parameter using that name. For instance, in our UserSingleComponent, we will be able to get a username variable thanks to that :username route parameter.

Adding This Section and Lazy Loading

The last piece of this puzzle is to add this UsersModule, its router and its components to our main application. We've created all these cool things, but our main application has no idea how to use it. Normally you would import this into the imports section of your main AppModule. That would load all these assets when our application starts up.

Since we only want to load these assets when a visitor visits any /users page, we'll use Angular's router to handle lazy-loading.

Lazy loading is a very simple task thanks to Angular.

Adding the Users Routes

Go into your app-routing.module.ts. Add the following route below our already existing home and contact routes:

const routes: Routes = [
  {
    path: '',
    pathMatch: 'full',
    component: HomeComponent
  },
  {
    path: 'contact',
    component: ContactComponent
  },
  {
    path: 'users',
    loadChildren: 'app/users/users.module#UsersModule'
  }
];

We've added a new path for the users route. Instead of loading the component however, we are telling Angular to lazy load this section using the loadChidren property. This notifies to Angular that it should load all the assets in UsersModule when we visit this route.

Adding a Users Link to the Header

We have wired up our /users section but we haven't yet created a link to get to it. Let's jump into header.component.ts and quickly add a link for the users section:

<a class="navbar-item" routerLink="users">Users</a>

Checking that Lazy Loading Works

Now we should be able to click the users link and see our new users section. You can see user-list works!.

Now to double check to make sure that lazy-loading actually works, we can open dev tools and visit the Network tab. Reload the home page and as soon as you click the Users link, you should see a new JS file loaded!

That users.module.chunk.js loads only when we visit the users section!

Nahoru
Tento web používá k poskytování služeb a analýze návštěvnosti soubory cookie. Používáním tohoto webu s tímto souhlasíte. Další informace