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
Mounika said…
Really you have done great job,There are may person searching about that now they will find enough resources by your post
python course in pune
python course in chennai
python course in Bangalore
Unknown said…
Great post! I am actually getting ready to across this information, It’s very helpful for this blog.Also great with all of the valuable information you have Keep up the good work you are doing well.
Best Devops training in sholinganallur
Devops training in velachery
Devops training in annanagar
Devops training in tambaram
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
tamilsasi said…
Inspiring writings and I greatly admired what you have to say , I hope you continue to provide new ideas for us all and greetings success always for you.
Keep update more information..


Selenium training in bangalore
Selenium training in Chennai
Selenium training in Bangalore
Selenium training in Pune
Selenium Online training
Selenium interview questions and answers
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
Aditi Ray said…
Home Mart is a site about Home Improvement, Furniture, Home Appliances and many more.
Check out the best
home office desks nz
coffee table nz
bookshelves
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
nice information on data science has given thank you very much.
Data Science Training in Hyderabad
Tech Guy said…
Nice Blog
For Data Science training in Bangalore, Visit:
Data Science training in Bangalore
zuan said…
Thanks for sharing an informative blog keep rocking bring more details.I like the helpful info you provide in your articles. I’ll bookmark your weblog and check again here regularly. I am quite sure I will learn much new stuff right here! Good luck for the next!
Web Design Training in Chennai | Web Designing Training and Placement
Web Designing Classes in Chennai | Web Designing Institute in Chennai
mobile application development training course in chennai
data science course in chennai
Tanika Co Valda said…
Great Article. As I read the blog I felt a tug on the heartstrings. it exhibits how much effort has been put into this.
IEEE Projects for CSE in Big Data

Spring Framework Corporate TRaining

Final Year Project Centers in Chennai

JavaScript Training in Chennai

norhan said…

اعالى الخليج تقدم افضل خدمات نقل العفش الدولى المتميزه باسعار متميزة ومنها :

شركة شحن عفش من الرياض الى الامارات
نقل عفش من الرياض الى الاردن شركة شحن عفش من الرياض الى الاردن

Myclasstraining said…
Thanks for one marvelous posting! I enjoyed reading it; you are a great author. I will make sure to bookmark your blog and may come back someday. I want to encourage that you continue your great posts.

sap hybris training in bangalore

sap scm training in bangalore

sap pm training in bangalore

sap crm training in bangalore

sap ewm training in bangalore

Really awesome blog!!! I finally found great post here.I really enjoyed reading this article. Thanks for sharing valuable information.
Data Science Course
Data Science Course in Marathahalli
Data Science Course Training in Bangalore
priyanka said…
wonderful article. Very interesting to read this article.I would like to thank you for the efforts you had made for writing this awesome article. This article resolved my all queries.
Data science Interview Questions
Data Science Course
priyash said…
Very interesting to read this article.I would like to thank you for the efforts you had made for writing this awesome article. This article inspired me to read more. keep it up.
Correlation vs Covariance
Simple linear regression
Awesome blog. I enjoyed reading your articles. This is truly a great read for me. I have bookmarked it and I am looking forward to reading new articles. Keep up the good work!

Data Science Institute in Bangalore
This is an excellent post I seen thanks to share it. It is really what I wanted to see hope in future you will continue for sharing such a excellent post.
Data Science Course in Bangalore
If you don"t mind proceed with this extraordinary work and I anticipate a greater amount of your magnificent blog entries
Data Science Training in Bangalore
Keerthi said…
Nice and informative read

Thank You


data science course in indore
varsha said…
My spouse and I love your blog and find almost all of your post’s to be just what I’m looking for. Can you offer guest writers to write content for you? I wouldn’t mind producing a post or elaborating on some the subjects you write concerning here. Again, awesome weblog!
AWS training in chennai | AWS training in annanagar | AWS training in omr | AWS training in porur | AWS training in tambaram | AWS training in velachery

Gaurav said…
This comment has been removed by the author.
Awesome blog. I enjoyed reading your articles. This is truly a great read for me. I have bookmarked it and I am looking forward to reading new articles. Keep up the good work!
Data Science Certification in Bangalore
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.
data science training in guduvanchery
Ziarulunirea.ro said…
Very interesting blog. Many blogs I see these days do not really provide anything that attracts others, but believe me the way you interact is literally awesome.You can also check my articles as well.

Data Science In Banglore With Placements
Data Science Course In Bangalore
Data Science Training In Bangalore
Best Data Science Courses In Bangalore
Data Science Institute In Bangalore

Thank you..
mary Brown said…
Great Article
Cloud Computing Projects


Networking Projects

Final Year Projects for CSE


JavaScript Training in Chennai

JavaScript Training in Chennai

The Angular Training covers a wide range of topics including Components, Angular Directives, Angular Services, Pipes, security fundamentals, Routing, and Angular programmability. The new Angular TRaining will lay the foundation you need to specialise in Single Page Application developer. Angular Training
EXCELR said…

Thank you for sharing such a really admire your post. Your post is great!
data science course in Hyderabad
priyash said…
Very interesting to read this article.I would like to thank you for the efforts you had made for writing this awesome article. This article inspired me to read more. keep it up.
Correlation vs Covariance
Simple linear regression
data science interview questions
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
Radley Co Tad said…
Great Article
Cloud Computing Projects


Networking Projects

Final Year Projects for CSE


JavaScript Training in Chennai

JavaScript Training in Chennai

The Angular Training covers a wide range of topics including Components, Angular Directives, Angular Services, Pipes, security fundamentals, Routing, and Angular programmability. The new Angular TRaining will lay the foundation you need to specialise in Single Page Application developer. Angular Training

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
Maneesha said…
As a matter of fact I read it yesterday yet I had a few considerations about it and today I needed to peruse it again in light of the fact that it is very elegantly composed.
data science
Amazing post found to be very impressive while going through this post. Thanks for sharing and keep posting such an informative content.

360DigiTMG PMP Certification Course
hrithiksai said…
This Was An Amazing ! I Haven't Seen This Type of Blog Ever ! Thankyou For Sharing, data sciecne course in hyderabad
360digiTMG said…
I am really enjoying reading your well written articles. It looks like you spend a lot of effort and time on your blog. I have bookmarked it and I am looking forward to reading new articles. Keep up the good work.
360DigiTMG
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
Terrific post thoroughly enjoyed reading the blog and more over found to be the tremendous one. In fact, educating the participants with it's amazing content. Hope you share the similar content consecutively.

360DigiTMG Data Analytics Course
priyanka said…
Amazing Article ! I would like to thank you for the efforts you had made for writing this awesome article. This article inspired me to read more. keep it up.
Simple Linear Regression
Correlation vs covariance
data science interview questions
KNN Algorithm
Logistic Regression explained
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
CloudLearn ERP said…
The content that I normally go through nowadays is not at all in parallel to what you have written. It has concurrently raised many questions that most readers have not yet considered.
Data Science training in Mumbai
Data Science course in Mumbai
SAP training in Mumbai

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
Cyber Security said…
Nice Information Your first-class knowledge of this great job can become a suitable foundation for these people. I did some research on the subject and found that almost everyone will agree with your blog.
Cyber Security Course in Bangalore
Writing in style and getting good compliments on the article is hard enough, to be honest, but you did it so calmly and with such a great feeling and got the job done. This item is owned with style and I give it a nice compliment. Better!
Cyber Security Training in Bangalore
TECHNOLOGY said…
I will very much appreciate the writer's choice for choosing this excellent article suitable for my topic. Here is a detailed description of the topic of the article that helped me the most.
unindent does not match any outer indentation level
Techprograms said…
I'm glad I found this blog! Occasionally, students want to know the keys to writing productive literary essays. Your first-class knowledge of this great job can become a suitable foundation for these people. Good
unindent does not match any outer indentation level python
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.
Google offers advertisements which appear in search results on google.com with the use of Google AdWords or advertisements that
appear on other websites through the Display Network and Google’s AdSense program.
With google ads you can appear in the top for searched keywords.Thus you will receive more relevant customers for your business.
Google Ads Services
You can get Apple-certified repairs and service at the Apple Store or with one of our Apple Authorized Service Providers.
mobile phone repair in North Olmsted
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
Artificial Intelligence training in chennai - Artificial Intelligence is programming that helps machines to think and work the same as humans. Join the Best AI Training Institute in Chennai
RPA Training Institute in Chennai - RPA robots utilize the user interface to capture data and manipulate applications just like humans do. join the Best RPA Training Institute in Chennai now.

Load runner training in Chennai - Load runner Software is an automated performance and testing product from Hewlett- Packard for examining System behavior performance. Join the Best Load Runner Training Institute in Chennai now.

apache Spark training in Chennai - Apache Spark is an open-source distributed general-purpose cluster-computing framework.Join the Best Apache spark Training in Chennai now.

mongodb training in chennai - MongoDB is one of the leading NoSQL databases and it is quite an interesting option in a row of open sources.Join the Best MongoDB Training in Chennai now.

Chennai IT Training Center
I am glad that i found this page ,Thank you for the wonderful and useful posts enjoyed reading it ,i would like to visit again.
Data Science Course in Mumbai
I need to communicate my deference of your composing aptitude and capacity to make perusers read from the earliest starting point as far as possible. I might want to peruse more up to date presents and on share my musings with you.
360DigiTMG big data course in malaysia
360DigiTMG said…
Nice and very informative blog, glad to learn something through you.
data science in malaysia
Devi said…
Sharing the same interest, Infycle feels so happy to share our detailed information about all these courses with you all! Java Training in Chennai & get to know everything you want to about software trainings.
360DigiTMG said…
Nice article. I liked very much. All the information given by you are really helpful for my research. keep on posting your views.
best data science course

Well we really like to visit this site, there is a lot of useful information we can get here.
Data Science Training
360DigiTMGNoida said…
Wow, amazing post! Really engaging, thank you.
data science certification in noida
I am another client of this site so here I saw different articles and posts posted by this site,I inquisitive more enthusiasm for some of them trust you will give more data on this points in your next articles. data scientist certification
Highly appreciable regarding the uniqueness of the content. This perhaps makes the readers feels excited to get stick to the subject. Certainly, the learners would thank the blogger to come up with the innovative content which keeps the readers to be up to date to stand by the competition. Once again nice blog keep it up and keep sharing the content as always.
Data Science Training
Maneesha said…
This is my first time I visit here. I found so many engaging stuff in your blog, particularly its conversation. From the huge loads of remarks on your articles, I surmise I am by all account not the only one having all the recreation here! Keep doing awesome. I have been importance to compose something like this on my site and you have given me a thought.
data scientist training and placement
Pallavi reddy said…
i am glad to discover this page : i have to thank you for the time i spent on this especially great reading !! i really liked each part and also bookmarked you for new information on your site.
data science training in bangalore
Sunil 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.
I want to leave a little comment to support and wish you the best of luck.we wish you the best of luck in all your blogging enedevors.
data analytics courses in bangalore
Truly mind blowing blog went amazed with the subject they have developed the content. These kind of posts really helpful to gain the knowledge of unknown things which surely triggers to motivate and learn the new innovative contents. Hope you deliver the similar successive contents forthcoming as well.

data science in bangalore
senthilr7692 said…
Thanks for sharing this blog with required contents.
AWS Course in Chennai
AWS Course in Bangalore
Honestly speaking this blog is absolutely amazing in learning the subject that is building up the knowledge of every individual and enlarging to develop the skills which can be applied in to practical one. Finally, thanking the blogger to launch more further too.

data science course in bangalore with placement
I am really happy to say it’s an interesting post to read . I learn new information from your article , you are doing a great job . Keep it up

Devops Training in Hyderabad

Hadoop Training in Hyderabad

Python Training in Hyderabad

Tableau Training in Hyderabad

Selenium Training in Hyderabad
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

princika said…
I want to leave a little comment to support and wish you the best of luck.we wish you the best of luck in all your blogging enedevors.
data science training in chennai
anu said…
Great post. keep sharing such a worthy information
 AWS Training in Chennai 
 AWS Training in Bangalore
I would like to thank you for the efforts you have made in writing this article. I am hoping for the same best work from you in the future as well..
data scientist training and placement in hyderabad
I am genuinely thankful to the holder of this web page who has shared this wonderful paragraph at at this place
data scientist training and placement in hyderabad
princika said…
I want to leave a little comment to support and wish you the best of luck.we wish you the best of luck in all your blogging enedevors.
data science training in chennai
ram said…
Train yourself in specific software modules to brush up your skills & shine in your career growth with the best software training institute in Chennai, Infycle Technologies. Infycle offers the Best Data Science Training in Chennai to serve the candidate's job profile requirements, including the top job placements in the MNC's. Rather than just teaching the theories, our fundamental aim is to make you a master by giving you live hands-on training. Therefore, individuals will be asked to work on the live tasks & real-time use cases that bring out the definite coder in you! To grab all these, call 7502633633 for a free demo.
This post is very simple to read and appreciate without leaving any details out. Great work!
data scientist courses aurangabad
I was just examining through the web looking for certain information and ran over your blog.It shows how well you understand this subject. Bookmarked this page, will return for extra. data science course in vadodara
Data Scientist said…
I truly appreciate just perusing the entirety of your weblogs. Just needed to educate you that you have individuals like me who value your work. Unquestionably an extraordinary post. Caps off to you! The data that you have given is exceptionally useful.data science training in chennai
anonymous said…
I want to leave a little comment to support and wish you the best of luck.we wish you the best of luck in all your blogging enedevors.
business analytics courses
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
I was actually browsing the internet for certain information, accidentally came across your blog found it to be very impressive. I am elated to go with the information you have provided on this blog, eventually, it helps the readers whoever goes through this blog. Hoping you continue the spirit to inspire the readers and amaze them with your fabulous content.

Data Science Course in Faridabad
Extremely overall quite fascinating post. I was searching for this sort of data and delighted in perusing this one. Continue posting. A debt of gratitude is in order for sharing. data scientist course in delhi
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
Extremely overall quite fascinating post. I was searching for this sort of data and delighted in perusing this one. Continue posting. A debt of gratitude is in order for sharing. data analytics course in delhi
annoymous said…
I want to leave a little comment to support and wish you the best of luck.we wish you the best of luck in all your blogging enedevors.
iot course in bangalore
princika said…
I want to leave a little comment to support and wish you the best of luck.we wish you the best of luck in all your blogging enedevors.
iot training in hyderabad

Popular posts from this blog

Configure PostgreSQL and phpPgAdmin in WAMP

Angular - 4 year road map

Flash FLV player using PHP