Angular 4 - Modules, components and routing

In the previous post we created a new Angular 4 project. Lets check the how to add modules, components and routing.

You could check out the code from here.
git checkout -b part2.0 origin/part2.0

We are going to use bootstrap styling . So lets add bootstrap in our aplication . We are going to use only styling not the components.

npm install bootstrap@3

We need to add the bootstrap stylesheet in tha .angular-cli.json.


"styles": [
        "../node_modules/bootstrap/dist/css/bootstrap.min.css",
        "styles.css"
      ],

Our first Module

Lets add a new module employee. Inside "src/app" run

ng generate module employee
or
ng g m employee

Wait we are going to lazy load this module , so we need routing inside the module, right? So we are going to create the routing also.
ng g m employee --routing

Time for component

It will create new employee module with its own routing. lets add a component for listing the employee. So inside employee folder run

ng g c employee-list

If you check the employee.module.ts you will find the component in imported and declared in the module, so it will be available for the particular module.
Now we need a service to communicate with API. Lets create that also. So inside employee folder run

ng g s employee

We need a modal to save employee. So we create a class employee . So in the same folder run
ng g class employee

Routing- lets got the page

So we created all the necessary files . But wait how we are going to load it?

First we will add the routing in the app routing for lazy load the module.
  {
    path: 'employee',
    loadChildren: './employee/employee.module#EmployeeModule',

  },{
    path: '**',
    redirectTo: 'employee',
    pathMatch: 'full'
  }

Add these routes inside the const routes .

So now it will redirect to the employee route. But wait where is our list component. We need to add the sub routes and modules in the employee routing file. So in the employee-routing.module.ts change the routes like
const routes: Routes = [{
  path: "",
  children: [{
    path: "list",
    component: EmployeeListComponent
  }, {
    path: "",
    redirectTo: 'list',
    pathMatch: 'full'
  }]
}];

Don't forget to import EmployeeListComponent. Now you can see the employee works .

API / Service

Now we need to load data from the API to list the employees. Before that we need to create the data modal for employee. So in employee.ts file add
export class Employee {
    department: string;
    gender: string;
    name: string;
    _id: string;
}

What we are going to do is, we will have our own services inside each feature module for API calss. Where we will set the API urls and its logic. So in our employee.service.ts we will first inject the angular http service.

constructor(private http: Http) { }

lets create a function to get employees from the API.
getEmployees() {
    return this.http.get(base_url + "employee").map((data: Response) => {
      return data.json()
    });
  }

The http service returns a Observable so we will subscribe to this in the list component.  So we are going to inject this EmployeeService inside the list component.

constructor(private empService:EmployeeService) { }

At this time the cli will throw an error that there is provider for this service.

ERROR Error: Uncaught (in promise): Error: No provider for EmployeeService!

We need to provide this service in employee module. Please read more about service in here.
So add the service to the employee module provider. So in NgModule decorator after declarations add

providers: [EmployeeService]

At this time you migh get another error like

ERROR TypeError: this.http.get(...).map is not a function

This is because we need to import the map from rxjs .

import 'rxjs/add/operator/map';

So that's it now we can call the API and render the result. So in employee-list.component.ts we will call the function.

getEmployees(){
    this.empService.getEmployees().subscribe(data=>{
      console.log(data);
      this.employeelist = data;
    })
  }
  ngOnInit() {
    this.getEmployees();
  }


For knowing more about the ngOnInit read the lifecycle hooks in Angular documentation.

Couple of points need to rememember:

  • In employee.service.ts the base_url needs to be your API end point. Later we will set in a single point. For current requirement we just keep as its is.
  • Also we have config.ts in the src folder which will have the base_url that you need update the API end point.
  • In the map we will convert the response, which in string format, will be converted to JSON.
  • Finally you have to import HttpModule from @angular/http in the employee.module.ts for http service to work
  • We will have a SharedModule which will not be lazy loaded, and includes the header component. We will add in app.component.html
And finally here is our employee module


Just like this add a new module and test it. I created  a project module that you could try.

Comments

Popular posts from this blog

Angular4 - primeng, ngx-bootstrap

Configure PostgreSQL and phpPgAdmin in WAMP

MEAN js Application structure

Change Android AVD location in Windows7