Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

.NET Core 2.0 With Angular 4 and MySQL, Part 10: Angular Lazy Loading

DZone's Guide to

.NET Core 2.0 With Angular 4 and MySQL, Part 10: Angular Lazy Loading

Welcome back! Picking up where we left off last time, we'll implement a subscription to our HTTP requests in order to display data on our page.

· Web Dev Zone ·
Free Resource

Deploying code to production can be filled with uncertainty. Reduce the risks, and deploy earlier and more often. Download this free guide to learn more. Brought to you in partnership with Rollbar.

As a continuation to a previous post (in which I've shown you how to use subscription), we are now going to implement that subscription to our HTTP requests in order to display the data on the page. Furthermore, we are going to use an advantage of lazy content loading, by using another module in our application - the owner module.

If you want to see all the basic instructions and complete navigation for this series, check out the following link: Introduction page for this tutorial.

For the previous part check out: Part 9 - Creating Angular4 client-side - HTTP, Services and environment files

The source code is available at GitHub .NET Core, Angular 4 and MySQL. Part 10 - Source Code

Creating a New Module

So let's start.

Create a new folder and name it owner. Inside create a new file and name it owner.module.ts. As you might have noticed, we are creating a new module inside the application which is going to be responsible for all the owner operations.

Let's modify the owner module:

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

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

There are two small differences between this module file and app module file. The first difference is that in the app module file we have an import statement for the BrowserModule, and in the owner module file, we have an import statement for the CommonModule. This is because the BrowserModule is only related to the root module in the application.

The second difference is that we don't have a providers array inside the owner module file. That's because we should register all the services in the root module. That way components will inject the same instance of the service only once and you can keep the state in your service.

Of course, if you really want to register a service inside any child module, you could just add a providers array. But, by doing so you cannot keep the state inside your service because every time we create a new instance of that component a new instance of a service is created.

Owner Component and Lazy Loading

Let's start with the creation of the owner component files.

Execute the AngularCLI command for creating a new component:

ng g component owner/owner-list

This command is going to create the required folder structure and it is going to import this component inside the owner.module.ts file as well:

What we want now is, when we click on the "Owner-Actions" menu, to show the content from this components HTML file. So first, just for testing purposes, modify the owner.component.html file by adding one paragraph (<p> tag):

<p>This is owner-list component page.</p>

Now modify the app.module.ts file:

RouterModule.forRoot([
      { path: 'home', component: HomeComponent },
      { path: 'owner', loadChildren: "./owner/owner.module#OwnerModule" },
      { path: '404', component : NotFoundComponent},
      { path: '', redirectTo: '/home', pathMatch: 'full' },
      { path: '**', redirectTo: '/404', pathMatch: 'full'}
    ])

With the modified part of the code, we are configuring the app.module to load the owner module whenever someone searches for the http://localhost:4200/owner endpoint. As you might have noticed, we are using the loadChildren property which means that owner module with its components won't be loaded until we explicitly ask for them. By doing this, we are configuring lazy loading from the owner module content.

Now if you navigate to the Home page, you will get only resources from the root module, not from the owner module. And, only by navigating to the owner-actions menu, you will load the owner module resources into the application.

Routing for the Owner Module

Let's modify the owner.module.ts:

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

import { OwnerListComponent } from './owner-list/owner-list.component';

@NgModule({
  imports: [
    CommonModule,
    RouterModule.forChild([
      { path: 'list', component: OwnerListComponent }
    ])
  ],
  declarations: [
    OwnerListComponent
  ]
})
export class OwnerModule { }

With this setup, we are exposing our OwnerListComponenton the http://localhost:4200/owner/list endpoint. Moreover, we are using the RouterModule.forChild function and not the forRoot function. This is the case because we should use the forRoot function only in the root module of the application.

Now we have to modify the menu.component.html file:

<ul class="nav navbar-nav">
      <li><a [routerLink]="['/owner/list']" routerLinkActive="active" 
                [routerLinkActiveOptions]="{exact: true}">Owner Actions</a></li>
      <li><a href="#">Account Actions</a></li>
</ul>

Excellent.

Now we know how to set up the routing for the child module, and for the component inside that module as well.

Interface, Subscription, and Data Display

Let's continue on.

When we navigate to the Owner Actions menu, we want to show all of the owners to the user. So that means when the owner component loads, the app automatically gets all the owners from the server.

To accomplish that, let's create a new folder, inside the app folder, and name it _ interfaces. Inside that, create a new file called owner.model.ts.

Modify that file:

export interface Owner{
    id: string;
    name: string;
    dateOfBirth: Date;
    address: string;
}

Modify owner.component.ts:

import { Component, OnInit } from '@angular/core';
import { RepositoryService } from 'app/shared/services/repository.service';
import { Owner } from './../../_interfaces/owner.model';

@Component({
  selector: 'app-owner-list',
  templateUrl: './owner-list.component.html',
  styleUrls: ['./owner-list.component.css']
})
export class OwnerListComponent implements OnInit {
  public owners: Owner[];

  constructor(private repository: RepositoryService) { }

  ngOnInit() {
    this.getAllOwners();
  }

  public getAllOwners(){
    let apiAddress: string = "api/owner";
    this.repository.getData(apiAddress)
    .subscribe(res => {
      this.owners = res as Owner[];
    })
  }
}

As you might have noticed, we have a property with the name owners and it is of type Owner array. Following this, we execute the subscribe function, which is going to populate that property with all the owners of the server. We're aiming to use the owners property to create our owner HTML page.

To accomplish that, modify the HTML component:

<div class="row"> 
  <div class="col-md-offset-10 col-md-2">
    <a href="#">Create owner</a>
  </div>
</div>
<br>
<div class="row">
  <div class="col-md-12">
    <div class="table-responsive">
      <table class="table table-striped">
        <thead>
          <tr>
            <th>Owner name</th>
            <th>Owner address</th>
            <th>Date of birth</th>
            <th>Details</th>
            <th>Update</th>
            <th>Delete</th>
          </tr>
        </thead>
        <tbody>
          <tr *ngFor="let owner of owners">
            <td>{{owner.name}}</td>
            <td>{{owner.address}}</td>
            <td>{{owner.dateOfBirth | date: 'dd/MM/yyyy'}}</td>
            <td><button type="button" id="details" class="btn btn-default">Details</button></td>
            <td><button type="button" id="update" class="btn btn-success">Update</button></td>
            <td><button type="button" id="delete" class="btn btn-danger">Delete</button></td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>
</div>

We could split this HTML file into two components (the parent component, OwnerList, and the child component, Owner), but because I didn't explain how to use child components, and I am going to in the next post, we are going to leave it like this for now.

We are using some basic Bootstrap classes to create a table for showing the owner's data. Inside that table, we are looping (with *ngFor) through all the owners. Then by using interpolation {{}}, we are showing owner properties on the page. For the dateOfBirth property, we are using just the Date pipe to format it the way we want to see it on a screen.

In our application, we are going to use date format MM/DD/YYYY, but in here we are going to use DD/MM/YYYY just to demonstrate the way to change the format with pipes without too much effort.

Conclusion

By reading this post you have learned:

  • How to create a new module and what imports to use.
  • The way to configure lazy loading and how it can help your application.
  • How to execute HTTP requests with a subscription and to display the resulting data on the page.
  • The way to reformat your date type when displaying it.

Thank you for reading the post, hopefully, it was helpful to you.

In the next part of the series, I am going to show you my way of error handling while sending HTTP requests. Moreover, we are going to create a Details page for the single owner.

For any suggestions or questions, don't hesitate to leave the comment in the comment section below.

Deploying code to production can be filled with uncertainty. Reduce the risks, and deploy earlier and more often. Download this free guide to learn more. Brought to you in partnership with Rollbar.

Topics:
web dev ,angular ,web application development ,lazy loading

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}