Angular services tutorial

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
this is per 25 of angular2 tutorial in this video we'll discuss why we need a service creating a service injecting and using this service and finally difference between a class constructor and ng on Annette lifecycle hook so first let's understand why we need a service in angular a service in angular is generally used when you need to reuse data or logic across multiple components anytime you see logic code beta access code duplicated across multiple components think about refactoring that piece of duplicated code into a service using a service ensures we are not violating one of the software principles don't repeat yourself the logic or data access is implemented once in a service and the service can be used across all the components in our application without the service you would have to repeat your code in each component imagine the overhead in terms of time and effort required to develop debug tests and maintain the duplicated code across multiple places instead of having that duplicated code at one central place like a service and reusing that service we're required now let's look at an example of creating a service in angular this is the same project that we have been working with so far in this video series notice at the moment within our employee list component we have the employee's data hard-coded instead let's move this responsibility of retrieving employee's data to a separate service and this component can call that service to retrieve the employees data the employee service which is going to retrieve employee's data is going to be in a separate type script file so let's place that type script file within the employee folder so let's right click on the employee folder add and we want to edit type script file and let's name this file employee dot service dot TS in angular a service is nothing but a class so let's create our service class let's start with export keyword so other components can in vote and use the service class if required class and in the name of our service class because we are using the service to retrieve employees data I'm going to call this service employee servers next let's decorate our employees service class with at injectable decorator before we can do that we need to import injectable from angular call now let's decorate the service class with at injectable we use this decorator to inject any dependencies into our service class at a moment our service class doesn't have any dependencies so we may remove this at injectable decorator and the service will still work exactly the same way however angular recommends whether your service have dependencies or not to always decorate it with at injectable decorator for consistency and future-proof for example tomorrow if you want to inject a dependency into your service you already have the injectable decorator so all you have to do is inject the dependency so for future proof angular recommends to always use the injectable decorator whether your service has a dependency or not next let's create a method within our employee service class which returns list of employee objects if you recollect in one of our previous videos we have created an interface which defines the shape of our employee object and that interface is present in this file an employee dot TS notice here we have an interface that defines the shape of the employee object so let's import this interface into our service class file so let's use the required import statement and then within the service class let's include a method let's name it get employees this method is going to return an array of AI employee objects for now let's hard-code the array of employee objects that we want to return and within our Employee List component within its connect constructor we have the array of employee objects that we want to return so let's cut this list from there and then specify it right here so at the moment we have hard-coded the list of employee objects that we want to serve this method to return in our next video well discuss how to retrieve these employee objects from a database server but now let's keep them hard-coded like that at the moment we have our service created now let's see how to inject and use this service from our Employee List component which is right here to be able to use the employee service within our Employee List component we will have to first import the employee service so let's include the required import statement next let's inject our employee service into Employee List component for that but in our class I'm going to introduce a private variable employee service whose type is employee service let's also introduce a parameter for our constructor the 3-meter name is employee service and type is employee service and within the constructor let's initialize the class private field underscore employee service with constructor parameter in a previous video we have discussed shorthand syntax to initialize class properties with constructor parameters we can use that shorthand syntax to reduce the number of lines in this piece of code right here so with the shorthand syntax we don't need this private variable and we also don't need this line within the constructor because we want a private field we are going to use private key word on the constructor parameter right here this is nothing but dependency injection in angular so with this piece of code in place when angular creates an instance of this Employee List component it also creates an instance of employee service and injects it into this component and we have this private variable which is initialized with that singleton instance and we can use that private variable to call the employee is service method which returns us an array of employee objects if dependency injection is not very clear don't worry well this is how it works in angular in detail in our upcoming videos for now understand that but an instance of this employee list component is created angular dependency injection system will automatically inject an instance of employee service into the constructor so let's use this private variable underscore employee service so this dot underscore employee service dot get employees and if you notice from intelligence this method returns an array of AI employee objects so let's use that value to populate this property employees so this dot employees equals whatever this method returns finally let's use the selector of this component list - employee as a directive within our route component so let's open our root component file which is AB dot component or TS and in the in-line template right here let's use the selector as a directive with all these changes in place let's run our application by pressing ctrl f5 notice we don't see anything on the webpage let's launch browser developer tools and investigate what's going on and if you look at the error message right here look at what it says it says no provider for employee service so basically angular is complaining that it can't find provider for employee service now if you look at our employee service the provider for employee service is this class itself so basically this error means that we will have to register or employee service with angular dependency injection system and the way we do that is by using providers property so we know that we need employee service with no employee list component so we have this add component decorator we also have a property for this deck later called providers so here we specify our service class and our service class is employee service so basically this is going to register the employee service but angular dependency injection system and this property is an area that means we can register more than one service and it's not a string so don't include it within single quotes so let's save this change and reload of webpage one more time and see what happens notice now we see the data as expected at the moment we have registered our employee service at this employee list component level this means employee service is registered with the angular injector at this component level so the service is available to this employee list component and to any of its children but it's not available for the other components this service can also be registered at a module level when a service is registered at a module level it is registered with the root angular injector so the service in this case is available for all the components in our application we will discuss this hierarchical angular dependency injection system in detail in our upcoming videos notice at the moment we are calling the service from the constructor the constructor is not the right place for service calls service calls are usually issued over HTTP to remove web servers if the network connection is slow or if the web server is busy processing other requests our service call could take some time to return the data we do not want this time consuming logic within the constructor so the obvious next question that comes to our mind is what is the right place for service calls ng on a net life cycle hook is the best place for service calls we discuss lifecycle hooks in our previous video ng honor net executes after the constructor and it's most commonly used for component initialization and making service calls so let's move this service call to ng on a net life cycle hook remember the steps to implement a life cycle hook that we discussed in our previous video the first step is to import the lifecycle hook interface in this case on init interface from angular core next we make this class implement that interface implements on in it and then finally provide implementation for the interface method which is ng on a net and then all we are going to do within this lifecycle hook is issue this service call so let's move that service call from the constructor to ng on a net lifecycle hook let's see what changes and freeload of web page notice it works exactly the same way as before so what's the difference between class constructor and ng on a net a class constructor is automatically called when an instance of the class is created it is generally used to initialize the fields of the class and its subclasses ng on a net is a life cycle hook method provided by angular ng own and it is called after the constructor and is generally used to perform tasks related to angular bindings for example ng on an it is the right place to call a service method to fetch data from a remote server you can also do the same using a class constructor but the general rule of thumb is tasks that are time consuming should use ng on a net instead of the constructor as fetching data from the remote server it's time consuming the better place for calling this service method is ng on the net as you can see within this example using the constructor to perform dependency injection which is usually quit and the service call is issued from ng on Annette lifecycle hook at the moment we have our employees data hard-coded within this employee service in our upcoming videos we'll discuss how to fetch this data from a remote server using the built in angular service HTTP so here is the employee service that we created earlier and here is the Employee List control and that needs employee service notice here we are using the providers property of the component decorator to register our employee service with angular dependency injection system we are then using the class constructor to inject employee service into this Employee List component and finally we are issuing the service call from ng on a net life cycle hook thank you for listening and have a great day
Info
Channel: kudvenkat
Views: 157,989
Rating: undefined out of 5
Keywords: angular 2 component constructor vs oninit, difference between constructor and ngoninit, why use services in angularjs, why use angular services, creating service in angular2, angular create service, angular create singleton service, angular service example, angular service dependency injection, angular service injection, angular service oninit, angular service singleton, angular service typescript, angular service youtube, angular 2 service example, angular2 service singleton
Id: qAeh4jZTjCk
Channel Id: undefined
Length: 13min 52sec (832 seconds)
Published: Wed Aug 02 2017
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.