This course has been updated! We now recommend you take the Angular 9 Fundamentals course.

Check out a free preview of the full Building Awesome Web Apps with Angular 2 course:
The "Services" Lesson is part of the full, Building Awesome Web Apps with Angular 2 course featured in this preview video. Here's what you'd learn in this lesson:

Lukas covers Services, specific tasks that can be used in Angular 2 components.

Get Unlimited Access Now

Transcript from the "Services" Lesson

>> Lukas Ruebbelke: Services, a service is generally by that 99% of the time, is a class 100% of the time. I've actually only ever used them as classes. But Pascal, there are ways that you can actually, essentially use an enom or a value. So when they go one, you can go dot value or dot constant.

[00:00:19] You can do that, but generally a service is just a class. And it should do one specific thing. So this is single purpose role, and what you want to do is take the burden of business logic out of your components, and put into a service. So it's going back to this graph, is you want to keep your components as thin as possible.

[00:00:44] So components really, in my opinion, have two jobs. One, to consume the data that it needs to satisfy its template. Secondly, is to capture user information and convey that to a service for handling. I see a hand coming up.
>> Speaker 2: Okay, so question again from Annie. Would the constructor ever run before the dom is finished rendering?

>> Lukas Ruebbelke: Yes.
>> Lukas Ruebbelke: Yes, that is a possibility. For instance, if within your you, the dom, was dependent on something that was still coming. So the constructural run before your bindings are completely initialized, which means that if your bindings aren't initialized, then certain things are not going to render.

[00:01:35] So that's absolutely why we use or we use life cycle hooks. Specifically to make sure that something doesn't run before the dom is even done rendering, or even able to render.
>> Lukas Ruebbelke: So it's considered best practice to always use injectable so that the metadata is generated correctly. So technically you can write a service that doesn't use injectable, but if that service has any dependencies, in other words you're trying to inject something else into it, it will fail.

[00:02:16] So just by default, I always make it a point to put just Injectable on top of my service. So you can see here, it's just a class, and we're just going @Injectable. Remember they're functions so you always have to call them, this will be a got you. I'm certain somebody's going to forget to put that in there.

[00:02:42] The parenthesis, and something your gonna throw an error. And so we have here, just a class methods properties constructors, and we make it available through Injectable. And then we, as we saw in the ng module, then you just have to import it, and then add it into your providers array.