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

afiah b said…
Excellant post!!!. The strategy you have posted on this technology helped me to get into the next level and had lot of information in it.
Java interview questions and answers

Core Java interview questions and answers

Java training in Chennai | Java training in Tambaram

Java training in Chennai | Java training in Velachery
kevin antony said…
I appreciate your efforts because it conveys the message of what you are trying to say. It's a great skill to make even the person who doesn't know about the subject could able to understand the subject . Your blogs are understandable and also elaborately described. I hope to read more and more interesting articles from your blog. All the best.

rpa training in Chennai | rpa training in bangalore | best rpa training in bangalore | rpa course in bangalore | rpa training institute in bangalore | rpa training in bangalore | rpa online training
SRI said…
Read all the information that i've given in above article. It'll give u the whole idea about it.
microsoft azure training in bangalore
rpa training in bangalore
best rpa training in bangalore
rpa online training
Tony Chew said…
Kriteria kartu jackpot Capsa Susun Dragon >> Mendapatkan bonus jackpot sebesar 65% dari total jackpot di meja. Royal Flush >> Mendapatkan bonus jackpot sebesar 35% dari total jackpot di meja. Straight Flush >> Mendapatkan bonus jackpot sebesar 5% dari total jackpot di meja.
asikqq
dewaqq
sumoqq
interqq
pionpoker
bandar ceme terbaik
hobiqq
paito warna terlengkap
syair sgp
Programming is always have a huge knowledge for create a creativity website, how can we except.
web design training programs
php training center in chennai
magento developer training
divi said…
That blog was amazing, I am impressed with your thoughts. I got the best information from this site, It’s very useful to all and us. Thanks for sharing this post.web design company in velachery
Keerthi said…
Nice and informative read

Thank You


data science course in indore
Gaurav said…
This comment has been removed by the author.
360digiTMG said…
Really nice and interesting post. I was looking for this kind of information and enjoyed reading this one. Keep posting. Thanks for sharing.
analytics
tejaswini said…
I will truly value the essayist's decision for picking this magnificent article fitting to my matter.Here is profound depiction about the article matter which helped me more.360DigiTMG data science certification
Atheef said…
It has fully emerged to crown Singapore's southern shores and undoubtedly placed her on the global map of residential landmarks. I still scored the more points than I ever have in a season for GS. I think you would be hard pressed to find somebody with the same consistency I have had over the years so I am happy with that.
360DigiTMG
Data Science said…
Awesome article with top quality information and found very interesting looking forward for next blog thank you.
typeerror nonetype object is not subscriptable
360digitmg said…
This post is good enough to make somebody understand this amazing thing, and I’m sure everyone will appreciate this interesting things.
Best Data Science Courses in Hyderabad
BTree Systems said…
iot training in chennai - IoT Training in Chennai - Best IOT Training Institute and technology providing the course for the Internet of things in both basic and advanced versions with other training courses such as DevOps, AWS, Python.
DevOps training in chennai - Best DevOps training Institute and training in Chennai will help and make you to become a DevOps programmer.
blue prism training in Chennai - Best Blue prism training and technology in Chennai always provide better and complete guidance on the Trending technologies such as Blue prism and various other technology.
BTree Systems said…
uipath training in Chennai - Best Ui path training and technologies on Chennai offering a better course and solution at minimal cost work.
microsoft azure training in chennai - Best Microsoft azure training in Chennai offering course and guidance on the Microsoft Azure technology.
This comment has been removed by the author.
David said…
This comment has been removed by the author.
EXCELR said…
Im really impressed by it.I am happy for sharing on this blog its awesome blog I really impressed. thanks for sharing. Great efforts. data science training
Excelr Tuhin said…
https://www.excelr.com/data-science-course-training-hyderabad
Very good points you wrote here..Great stuff...I think you've made some truly interesting points.Keep up the good work.

Best Institutes For Digital Marketing in Hyderabad
Anonymous said…
Digital Marketing Course with Internship at Digital Brolly with 100% placement assistance.

Chennai IT Training Center

R programming training in chennai - The R programming course would help to multiply your knowledge in statistical and graphical counting. R includes many other series machine learning algorithms, linear regression & statistical inference.

blueprism training in chennai - Robotic Process Automation (RPA) software developed by Blue prism group. Actually Blue pro=ism is a latest technology and a leading tool for RPA. It is software which reduces human error and can icrease the efficency of organisation.

AWS Training Institute in Chennai - Amazon Web Services is one of the most commonly used cloud platform that presents you with all the features that required by any well-grown company at affordable price segement.
chitra said…
Amazing Information! keep updating your Blog like this.
Tally Course in Chennai
Tally Institute in Chennai
Maneesha said…
It was a good experience to read about dangerous punctuation. Informative for everyone looking on the subject.
data scientist training and placement in hyderabad

This post is very simple to read and appreciate without leaving any details out. Great work!
data scientist courses aurangabad
Rajendra Cholan said…
Want to set your career towards Big Data? Then Infycle is with you to make this into your life. Infycle Technologies gives the combined and best Big Data Hadoop training in Chennai, along with the 100% hands-on training guided by professional teachers in the field. In addition to this, the mock interviews for the placement will be guided to the candidates, so that, they can face the interviews with full confidence. Once after the mock interview, the candidates will be placed in the top MNC's with a great salary package. To get it all, call 7502633633 and make this happen for your happy life.

Best training n Chennai
Riya Raj said…
More impressive blog!!! Thanks for shared with us.... waiting for you upcoming data.
Python for Data Science
Learn Python for Data Science
Shiva Shakthi said…

More impressive Blog!!! Its more useful for us...Thanks for sharing with us...
Why is Big Data Important?
Why Big Data
Rajendra Cholan said…
Title:
Grab Oracle DBA Training in Chennai | Infycle Technologies

Description:

Set your career goal towards Oracle for a wealthy future with Infycle. Infycle Technologies is the best software training institute in Chennai, which gives the most trusted and best Oracle DBA Training in Chennai with hands-on practical training that will be guided by professional tutors in the field. In addition to this, the mock interviews will be given to the candidates, so that they can face the interviews with full confidence. Apart from all, the candidates will be placed in the top MNC's with a great salary package. To get it all, call 7502633633 and make this happen for your happy life.
best training institute in chennai
karthick said…
This post is so helpfull and attractive.keep updating with more information...
Data Science Requirements
Career In Data Science
David Fincher said…
This post is so interactive and informative.keep update more information...
hadoop training in velachery
Big data training in chennai
Pavithra Devi said…
This post is so interactive and informative.keep update more information...
Angularjs training in anna nagar
Angularjs Training in Chennai

360DigiTMG said…
Really impressed! Everything is very open and very clear clarification of issues. It contains true facts. Your website is very valuable. Thanks for sharing.
data analytics course in hyderabad
This post is very simple to read and appreciate without leaving any details out. Great work!
data analytics training in aurangabad
Samia Beel said…
Free reimage repair 1.9.5.6 liscence key free download software at UpdateStar - Reimage repair:How It Works...With surgical precision, Reimage Crack
Links For You said…
Use MS Windows 7 Ultimate Product Keys to install Windows 7. No need for final activators, crack, or crucial fake generator products. Win 7 Ultimate Key
Farah Noor said…
Wish my love stays happy forever Forever at this time, It is the time to cheer aloud, Time to find a new meaning of love, Thanks for everything sweetheart, ..Short Christmas Wishes For Friends
tech said…
May the good times and treasures of the present become the golden memories of tomorrow for your lovely family, just as our childhood memories of .Short Christmas Wishes For Friends
Ravi Rajput said…
I read your blog post. It is one of the best informational content
We are offerd the SAP HR Training in Delhi
ramarajanmech said…
Really want to thank you for the wonderful post, keep going. inventory management system
360digiTMG.com said…
Nice blog. I was looking for a certification training course in Bangalore, and the 360DigiTMG course program will help me to become a skilled and certified data science professional. This article contains all the information that students and aspirants look forward to solving their doubts and getting a clear picture of how they can embark on their journey and stay ahead of others. Please keep updating and writing more wonderful and informative articles like this. Reading this article helped me a lot, and I hope more readers and students can clear their concepts after reading this post.
best data science institute in hyderabad
Anil said…
Are you looking to pursue a career in SAP SD and searching for the best training institute in Delhi? Look no further than ERP Training Delhi. Our comprehensive SAP SD Course in Delhi is designed to equip you with the necessary skills and knowledge to excel in your career.
Brijesh Sharma said…
At ERP Training Delhi, we understand the importance of staying up-to-date with the latest trends and technologies in EHS management. That's why we've developed a cutting-edge SAP EHS Course in Delhi that covers all aspects of environmental management, occupational health and safety, and product safety.
Sonam Singh said…
ERP TRAINING GURGAON. We offer comprehensive and industry-focused training programs to help you master SAP BW Training in Gurgaon and propel your career to new heights. Our experienced trainers and state-of-the-art infrastructure ensure a seamless learning experience. We understand the importance of a successful career transition. That's why we offer placement assistance to our students. Our strong industry connections and dedicated placement cell work tirelessly to help you secure rewarding job opportunities.
Anonymous said…
I'm immensely grateful for stumbling upon this article. It provided me with valuable insights and a fresh perspective on the topic. Try Now Digital Easy's google business email pricing

Popular posts from this blog

Configure PostgreSQL and phpPgAdmin in WAMP

Angular - 4 year road map

Flash FLV player using PHP