UPDATE (10th October 2017): This Angular 2 tutorial has been updated to the latest version of Angular (Angular 4). Note that the Angular team has re-branded the terms
Angular 2 to
Angular 1.x to
AngularJS which are now the official names of these frameworks.
This is the second article on the Getting Started with Angular 2 Step by Step series if you missed the first article go and check it out!
Ok! So you’ve learned how to get started with an Angular 2 and TypeScript application and you’ve written your first component. Yey! The next thing you are going to learn about are services and dependency injection.
In the previous example we had a
PeopleListComponent where we initialized an array of Star Wars persons of note. But your component shouldn’t know or care about where the list of people is coming from be it local storage, a database, a web service or the grace of the holy spirit.
That’s why we are going to extract that data access logic into a service that we’ll inject into our component through its constructor. Breaking your application in smaller pieces that have a single responsibility will make it much easier to reason about, more maintainable, reusable and testable. Win Win!