Angular 9 Fundamentals Services Exercise
This course has been updated! We now recommend you take the Angular 13 Fundamentals course.
Transcript from the "Services Exercise" Lesson
>> Now the challenge that I would like for everybody to do is, if we go back to our home component. What we have here is these courseLessons array. And so, what I wanna see happen is, challenge. Step one is, I would like you to create a lessons service.
[00:00:34] I'm gonna give you a hint, n gg, shared/services/lessons. I will do that with the D flag for a dry run. Step two is, add the lessons service to app module. Step three is inject lessons service into home component. And then step four is, Consume or move lessons to service and consume in component.
[00:01:28] All right, I'll push this back up as well.
>> Since the generator is provided in root, we shouldn't have to put the service in the provider, should we?
>> I think you can get away with it. So typically, I will just do that. So, I think you should try it and let me know.
>> The first one worked. I don't know if there's a reason why.
>> So one thing that you can do is, you'll notice when you generate it. Yeah, so the question is, when you generate your component, it does provided for root. So, if we hop over to this component, we'll see.
[00:02:17] And so what this does is this will go ahead and add it to your root module. And so, you could get away, without adding it to your module. But typically, what I will do, because there are cases where you don't wanna make a service available to your root component.
[00:02:39] But you want to essentially keep it at, maybe a lazy loaded module level. And so, just for the sake of exercise, because you could get away with it, is I do want you to add this to your app module. So, if it's provided in route, do you need to do it?
[00:02:58] No, but in terms of, sometimes in a subcomponent. And so, this is where, for instance, I'm on a very, very large application for a Fortune 100 Company, and everything is separated into lines of business. And so, if I have a service that's specific to that line of business, I do not want to use provided in root.
[00:03:20] Because I don't want to make it available to everything else. And so therefore, I manually will add it into the provider. So, that's a very good question, is if you have provided in root, do you need to add it into the providers of the module? The answer is no, but I want to do it both ways.
[00:03:38] So that you understand, or that you see that, this is where you would do it, if you're not providing root. Because there are going to be cases you're not going to want to do that. So, do you need to add this to providers, not necessarily, but for this case, I want you to do it to get the muscle memory.