Simplifying Dependency Injection, Services, and Providers in Angular

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hi welcome to another video by geek nine-seven in this video we are going to learn about dependency injection angular or in general working with services in angular I'm done enjoy kamagra so dependency injection is a pattern which creates a loosely coupled application where application is highly scalable and application is suitable for test-driven development so let us assume that you have various layers in your application such that UI layer business layer and data base layer if you're following inversion of control pattern or dependency injection pattern in that UI layer needs business layer but it would never create object or business layer directly instead of that it would ask some other component of the application to inject that business layer dependency in the UI layer as great Martin or follow writes in his blog that second application is special because it supports inversion of control is like saying a car is special because it supports you with any good scalable application or application which is loosely coupled must have inversion of control or dependency injection so to understand it let us go here and let's say that we have two UI in our application let us call this as UI one all right and then I have another UI here and let us call that as UI to in context of angular you can think this UI 1 + ey 2 as a component 1 and component 2 now we have a business layer which is right here let's call it business layer and then this business layer is talking to data access layer and if it is an angular application then it could be talking to API all right so now what happens that you need this business layer to display data in the UI so what is really you do you take this business layer and creates object of this directly inside this UI now since that object let's call that object as BL one BL o one now that'd be a no one the object of business layer directly created inside a y1 problem number one is this BL o one cannot be used inside you by two because you have created that inside u i1 and a second problem is this the purpose of UI 1 the purpose of that component is to render and UI and while creating object of this business layer for any reason if that object creation fails what had happened this UI creation would also fill and you you may not want that it may happen that whatever this business logic is returning to this UI is just only one portion of the UI and other portion are static but if the responsibility of creating this object creating the dependency object in the UI itself would make this business logic and UI logic UI layer very tightly coupled to each other so these two problems that this object or business layer is not reusable and for any reason if object creation inside UI one fills the whole UI would not render are two major problems but if you follow dependency injection what you can do instead of doing this let us say application will have one more application has one more let us call it one more component not that angular component but but a part of the application the whole purpose of this part is to create object and passed it to wherever it is needed so now in this case what would happen stood off if you I need this business layer object instead of doing this what we have done here it would go to this guy and say that hey can you give me object of being so this has information that if someone is asking object or BL then what this has to do whether it has to create new object or whether it has to use the existing object all this information is there configured in this particular portion of your application and depending on those configuration when I when a UI layer would request this it would create a new object or reuse the existing object and pass it on to UI layer in that case what will happen this UI layer is not actually creating the object and since it is not creating the object it may that dependency will get injected when available to this UI layer and only the portion where the that object is needed may get impacted if that dependency is not being injected correctly otherwise the static portion the passive portion of you I would not get impacted in the same way when UI to is needed so now you see that this is a it needs that dependency however it is not directly creating that it would also go to this sky which is called di container so this guy is known as di container dependency injection container and what it will do it will go there and now again depending on the configuration whether di container to create a new object or business logic or it would create a reuse existing object and return that to UI to so depending on the configuration it may happen the same object is being used in UI 1 ey 2 and further in UI 3 and so on and of course this has some information here we can in the DI container about business logic that how this if some if any UI or anywhere this business logic is dependent on how this di has to inject that and in the same way it would have this object of DL can be injected up in the business logic and so on so if you look at here what is happening these are very loosely coupled part of application this BL is dependent on DL but it is not creating object of DL directly in the same way you Y is dependent on BL but it is not creating object directly and there is there is a part of application whose so responsible is to find the dependency and inject the dependency it may use a new object it may use existing object depending on the configuration so more or less this is called di dependency injection and this is very popular it is not part of only angular any scalable application should have this pattern and since it is very useful since it is very required to create a scalable application and test-driven development application and angular is actually made for test event development you can create the whole application and and without having that UI you can be very sure that okay business logic is working fine only on the basis of the test which you have written so angle is very very much suitable for test development hence its suppose di in-house you don't have as a develop but you do not have to do anything extra for that by default angular framework supports di so again if we go back here asthma as it says motive about as Martin for followed he writes in his blog there saying an application is special because it supports inversion of control is like saying a carriage space and we got supports away so any good application should support di di ad it's first-class citizen all right so now you understood little bit about the di you can go on internet and it's completely tactical and learn a lot about it I prefer to use inversion of control and dependency injection interchangeably somewhere on some blog you may find that no they say these two are two different things but you can go and learn about those theories here let us focus you got little bit understanding about what is dependency injection that how we can work with that in angular so in this video what I'm going to cover I'm going to cover how to create an user service then we'll understand what is three shakable service and what is the concept of providers injectors you may have come across these two terms million times that providers injectors providers injectors but these are very simple terms and we try to understand them through the code then again when angular creates a new object and when it uses an existing one so this third point is very important if we go to our diagram here you see that angular will decide here that whether we need to pass a new object to the component or whether it needs to create a whether it's has to create a new object to pass to the component or whether it needs to use the existing one and that depends on the configuration so we will learn that also and this is again very important if you are writing a scalable application or you are appearing for a client interviewing job a job interview they they they confuse you on this once we learn that we would move ahead and understand different providers and these are very easy then we'd move to angular 9 options in angular and we have root in E in platform we try to understand what is that and then you'll see that how we can work with services in a lazy loaded model so to start with I have created an angular application in the angular application I have added two child components called child 1 and child 2 as you see on your screen and then we are using that component inside app component right here in child 1 and absent to be used here now to add a service in the application what we would go we would write here let's go and you just see a I'm gonna say like command in GG is and you can give any name of the service in GG is generate AC service let me give the name of my services log so what it will do it will create a service in the application so here it has created service and spec file for that and we are back here and you can see that this law service has created now if you look at this code there are a couple of things in line number six you can see that it is just a class then you can see that this class has injectable decorator and inside injectable decorator you have a property which is provide in and by default that value is say - root now what is meaning of that we would come to that later but before that let us go ahead and write some code in this service and we will try to use that so he'll be created a service and let's say that in the service we have a private static value count all right and then what we are doing here in the count in the constructor we are going to say that this dot count is equal to DS dot count plus one okay so it's not discount it should be because a static so we have to say log service dot count is equal to log service.com dot plus 1 and then console dot log log service dot count now what I'm doing you might have guessed as of now that I am I have just create I created a static variable and inside the constructor I am increasing that value and printing that value now you know from your object-oriented skill that that this constructor would be called as many times object of log service would get created so if application is creating object of log service twice then this constructor would be called twice if object of log services been created five times then this construct what we call five times and we would have five console dot log and if application is creating only one object then this logs construct would be called only once and we would have only one console dot log is it clear and then let's say that we have one function here called say hello' and this takes a parameter name string and then it just returns a Laplace name very simple service nothing fancy here only thing you need you should focus here that we are trying to print number of times the constructor of the service has been called now to use this let us go to the component wherever we want to use it so in the component child component this is the child component child to component the syntax we use it you have to inject that service now child to component has a dependency on log service so what we are going to do how we are going to think that in our mind visualize that in our mind that since child 2 has a dependency on log service so we need to inject log service inside child 2 component and the syntax to do that is say private let's say log service and log service that's it this is the syntax if you follow that syntax like in the constructor of the component or in PI orab directive if you follow the syntax we create a private variable of the type service service is a class which is decorated with injectable which you can go and check here alright so when you follow these syntax what angular does angular inject that angular assumes that child to component has a dependency on log service and angular injects that in that component alright and let us say that in the here we have 1 masses and message string and then we can say this dot masses is equal to this dot log service dot C hello and here let us pass it is child to so let's pass child to all right and then we can go ahead and display this masses in the child to component template and here we can say that instead of child to works just use interpolation and pass this message so let's take this message from here and we need to repeat the same thing in child one we want to display that exactly in the same way so here child one we say masses and then we can take exactly the same code and pass it in child to child one as well so he in the child one let's go and save message string pass inject lock service all right and then here instead of child to say child you want all right so if we have created a service we are using this service now to run this call ng serve and here again just to repeat a we created a service lock service dot ta stand inside this service you can see that this service is this class is decorated with injectable which makes this class as a service and by default these are provide in property which is say to root we would come back to this what does it mean and we have created a static variable and just increasing that to check that how many times this constructor would be called and then it has a simple say hello function all right so here we created that a compiled successfully and let's go here and here you see that we are getting hollow child 1 and hollow child 2 and in the console if you look at the console here you see that you are getting only one which means the constructor of service is called only once which means that only one object is surd between holo child 1 and Hollow child 2 right because if angular is creating more than one object and it would call that constructor here more than one time and if it is calling it more than once then of course this console dot log would be printed more than once but here you can see clearly it is only once being called that constructor is being called only once of the service which sees that angular has created only one object of the service and that object is being used in hollow child 1 in in child 1 component in the and child 2 component so what message I am trying to give it to you here is that when you when you generate a service with angular CLI command and and which when the property is said to provide in is equal to root that means that by default if you don't do any other changes by default of that is a kind of singleton service singleton service means angular is going to create only one object of that service for the whole application and the same object would be used everywhere you are using the service now provided in equal to providing equal to root has two information first only one object would get created until you don't do something further which I'll show you next and second this service is a tree shakable service if providing is it is said to root means this service is a tree say cable service tree shakable means if log service is not used anywhere in the application angular would not keep this log service as the part of the final output bundle this service would become a tree say cable and it would only become part of final output bundle if it is being used somewhere else otherwise angular is not going to keep it as a part of the application and that is very useful because that would reduce size of your application so I repeat if this providing is equal to root means Angra is going to create only one object for the whole application it goes onto the application module label and second this service is a tree shakable service so I hope now you understand what is meaning or provide in is equal to root all right now what I'm going to do if you have understood so far what I'm going to do in the Chuckle one component let me get up get rid of this style URL and here every component has something called providers property providers there's a question mark after providers missus is and a label it you can pass it or you can not pass value to it we want to pass it here so we'll say that hey providers and then it takes an array and here let's say log service so what I have done in the component a child one component I again I have I'm setting the value of providers all right I will have not done that for the child too so now if we run this application and let us run this you are getting exactly the same output but what you should focus is right here in the console you see that constructor is being called twice that's why we're getting two printed means angular has created two object of log service now the message here is that even if you created our angular app angular service following Angra see like using English CLI command and provide any is equal to say true is set to root it does not mean that always this service is a singleton service I have seen when I teach to people when I consult to projects that people assume that if providing is equal to root means always there would be only one object know by default it is only one object but if you go and provide this again like this what we did in child one angler is going to create more objects for that if you go again and provide it in that child to then again our object angler will create one more object so so the thumb rule is that angular will create as many object as many times this service is passed in the providers throughout the application regardless whether it is said to root alright so I hope you understood so far now that what is the purpose of root it makes a tree say Kamel service it creates a singleton service until you don't go and do something like that when you explicitly pass it to the component now you have two objects of the log service the object which is created inside child one would we have been able to child one and all that child component of child wanna a repeat object which is created here inside child one would be available to child one and all the route component of child one and the another object would be available to the whole application now next let us do one thing let us go ahead and remove this provide in is equal to route from the service all right so we have a service which is decorated with injector injectable and variable providing or equal to root and also we remove it from the providers area of the component all right now let's go and run the application when we run this app you see that here you are getting the error that no provider for log service and no provider for log service for getting that error twice because we are using log service at two places child component one and a child one component and child two component now what is happening here that it starts with this code when you see this code lock service log service this log service it may appear to you that this log service is actually the name of this class but in reality it is not that class it is the token that token which is being injected here actually it follows like this so step one you injected the token which we have done right here all right then step two what happens that angular goes to the I container and finds how service is provided how service for that particular token is provided whether angular has to create a new object whether angular has to use existing object and anger has to create object of which class where is that information right now in our application since we removed that from a four root of the service we do not have that information here and services nowhere provided and hence angular is giving us error in the step two so one option you know that you can go and pass it as providing equal to route which will make a tree say cable service and only one object will get created another option is you can go at the module level here I am going at the app dot model means this would be available throughout the application and in animating you see that you have providers array in the provider you can go and pass this log service when you did this actually we completed this step two now angular knows that okay whether angular has to create a new object whether angular has to use a existing object or whether an angular has to create object of which class and that information is given only by this one value when you pass to providers array on running the application you see that everything is back and there is only one object being created and of course if you want to create more than one object and for that particular component and sub child you want separate component you can again go and pass this information in the providers and here you say that okay log service and as it happened in for in the route option angular should behave exactly the same way you have one and two two objects being created now you may have a question that okay what is the difference then when we passed that in the app model and when we pass it as de for when we pass four root value providing is equal to root so the answer of that is before that let me get rid of these providers that when you pass in the log service here when you pass this as provide in as root it is a tree say cable means if this is not used this service is not used anywhere an array is going to tree set this service however when you pass this in the module now this service is not recyclable and this service regardless whether this locks service is used or not used angular is going to include that as a part of the final output bundle so this is one thing you need to keep in mind alright so let us go back to step two again now angular knows that okay it has to create a new object or use existing object and create object of which class and then it will inject that dependency so you may have a question that hey where you are providing that information that create object of which class by looking at this code you may see that okay it is creating object of log service but internally actually this information which we are passing in line number 18 is is represented like this where you say that provide the log service because you are using that everywhere so here we say that hey provide log service and whenever log service a token is provided please use the class in this case we want to use log class log service itself so when value of provide and huge class is same instead of representing it like this you can just pass log service now again if you go back here you say that hey inject that token so the token injected is here log service which is actually equal to you can think of this log service and then a step to e it says that ok create a new create object of which class which information is passed here that when this lock service token is injected please use object of log service class and in this configuration it means only one object would create it and that would be used and if you run the application you should get done or put only one object is created and you are getting expected output hello child 1 and hello child - so now you should understand that what is the meaning of huge class now you may have a scenario that ok can you give me a more example when huge class should be used so for that what I'm going to do here let me create one more object more service I'll say in GG is and let us call that updated log service it may happen that the sub data log service is inheriting the log service here you can you can very much do that it can inherit the log service or it can be entirely a different service implementing an interface and all that but it is going to have almost the same signature plus extra signature etc but here what I'm going to do I'm going to just copy this log service from there in the updated log service and I'll get rid of this providing equal to root here and then in the updated log service I'm saying that a private count zero and this is updated log use updated log service dot count and updated log service.com plus one and they're just alright so here what I'm going to say say hello and say hello name updated again just to give give you an example that how each class works I am doing this in real time sinner you will have real examples which I'll just give you next how you can use that so here it is I have one updated service now what I want this updated service maybe is calling a new version of API or we it has some extra properties let's say say not hello anything it has and you want now this say not hollow to available to everywhere where using log service and all that so hollow not hollow all right so here we have created a new service now see in the real time scenario what would happen that this new service should be created separately you need tested separately now it is available now you want to use it now to use this here what you want that you want everywhere where you are using log service instead of this log service class you want to use update a log service class and how you can do that is very simple you want it here wherever this log service is being used please use the class updated log service not log service and just we have to change at one place I change it here in the huge class and it's go and run this all right so now what would happen that angular here will go and this is injected log service which tape one injected a token log therapies go to a step two angle a DI container that how service is provided so create object of which class that information is available in the right here you select for lock service token which is injected please huge class of data lock service now everywhere you should have this updated lock service created and let's go and run this and here we are saying that you have holo updated child 1 and holo updated child 2 and again only one object is being created so if you have to change that class for a particular token you can do that now you may have a question that hey can you give me a real-time example of that I'll come and give you a real-time example but before that let us say that you added a new object company in your application and that component is let's say child 3 so we added a new component now we want that for the new component what you want so here you added a new component and for the new component child 3 everything is going to be same like other child but here what you want here you want to use the token updated lock service not the lock service alright so here you use that token updated lock service but in this case what would happen let's go and display this masses in the app child 3 and we can this varies here all right and then take this child three component AB child 3 dot T AB child 3 and go to app component dot HTML and to use that I will use that right here like this now what is happening in the child 3 component what I am doing I am using a different token and keep in mind this token updated lock service is not provided it if you go we have removed for the update a lock service if you go to definition we don't have any providing information available here and if we go to app module dot TS also that how that updated lock service token would be used isn't that information is not provided that means that of course angular would complain about this so let's go and run this year and here you see that it is giving you that no provider for updated log service so you can go and again a instruct angular to create provider for updated lock service token as well so here we are we are saying that ok provide a new token and we call this token as updated log service and here used a class of detail log service now when you use the class now you have two tokens log service and update a log service but if you follow this huge class and huge class they are going to create two objects separate object a separate object for lock service token and separate object for updated lock service token and here you can see that you have hello up to the child one holiday child to howl ability child too and here you see that one token got created for the token log service and another object got created for token updated log service so you can provide it now newly created object will can have this token and they can have the object of updated log service which is a latest version of service now what if you want to use the same object for both the token for the lock service and update a lock service in that case instead of this huge class you will use use existing now when you say that hey whenever this token updated lock service is provided please use the existing token log service and he will say that he use an existing topic token log service so what angular will do it will use the object for this large service provider so here I repeat what angular is doing for child 3 it will for the child 3 component it found updated locks Navi should go to app dot model here is a token provided then the syntax is use existing which means we are instructing that hey angular reuse the object which is for the lock service token for the log service token it is creating object of updated lock service class and the same object would be used so here you are back and here you can see that how it is creating for only one object and that one object is being used for both the token lock service and updated lock service so now you understand that how you can have two object a single object for two tokens and if you want to create separate object instead of huge existing you can create huge class lock service now if you say that lock service then it will create object of log service class for updated lock service token and we'll find output here hollow child too and I'm sure if you have your following up to here in the video you know that why you are getting the output hollow child too because we are saying that hey give me for updated lock service token please give me object of class log service here you can pass ABC any object you can pass it a pass it here alright so so this is how you can you now understand that how huge class and use existing works now let us see a real-time example of huge class we are going to use this huge class feature of angular dependency injection to handle the error globally in the application for example here let us go and put a button and I have a button here which is st. data and on the click of this button what we want we want to send data to API or something like that so here it is send data function and I have put this button in the app component and the app component that is let us go and create this function all right and then here we are saying that this dot data is equal to this dot URL dot index off of course line about hutton will throw error because value of URL is undefined and we are trying index of method on undefined so javascript is going to complain about that one way to handle this error is that you can put it in the try catch and do that but angular has error handler class and that should able to handle this error so let's see that what is happening now when you run the application everything looks good hello ability child to we don't want that that is actually child three dot component or DSL it is child three all right so let us go back to again this app component and run this and here we are everything looks good now we know when we click on the send data button that a function would be called and it should throw us error and here it is erroneous era that he cannot read property index of undefined now this error is brought to you by default error handler class of angular this error is good but what if you want to have a uniform global error handling for the application you don't want to use that error handler class which is given to you by angular and want to use your own error handler class and for that let's say that how we can do that so here what I'm going to do I'm going to create a new service and let's say that this service is global error and I'm giving it name as global air handler and this is created and it's going around this so here we have global air handler class created right here and we would say that okay now what we want we want to modify that default error handler class so for that let's go and in the global 1,100 class what we will do we will extend that default error handler class so for that here I'm here and saying that okay implements error handler is part of angular core all right and this error handler has one method called handle error and we can go and say that hey handle error and this takes error okay and here we'll just say console dot log there is no error in my application alright so we are not doing just we are consoling that a keep in mind this console can go to the server you can pass it to API log data to the service and all but here I'm just trying to show you that what I have done I have created a new service called global error handler and which is implementing error handler by default this error 100 is being used to handle error in angular application and we'll get rid of this providing a root as well alright so now again when you run the application you see when you click on send data you are getting an error that cannot read proper property index of undefined and that is coming due to a default error handler now what we want we don't want to use default error handler and we want to use global error handler service and now you should know the answer of that what we need to do for that for that we will go to at model dot RTS and in our model dot t-- s what we can say that hey angular will ever error handler token is injected please use glass and we created that class just now Global error handle service class so please use this class for error handler token and by default this error handler handles your exception in the application but right now we are overriding that and saying that use global error handler service which we just created where whenever a error is encountering what we are doing adjust displaying this message there is no error app error in app so now let's go and run this application here we are and when we click on send data you see that that default error is gone and there is no error in app that comes that information is coming to you and again throughout the application but if you want to use the default one you can pretty much go and say that use error handler itself and here it should use the error handler which is the default and you are getting this candidate property index off undefined but we don't we want to use our error handler and here we can say that use the global error handlers service of course in the global error handler service you not only print one information you can use some third-party libraries like stack trace dot J's and all and using that you can from here you can log this information to to the server you can handle at the application level what you want to do so this is a real time example of how this use class comes to the excel other example is HTTP interceptor angular provides you or dollar HTTP service which is used to make an API call if you want to overwrite there and use your default class for that you can again use this user hand use class and create a new service and inject that throughout the application so now I hope you understand what is the real purpose of this huge class you can use it for global error handling you can use it for HTTP intercept and of course you can use it for the versioning of your custom services which you are creating into the application besides huge class and existing we have use value in and use Factory now what use value is used for it is used to provide a value instead of object so if you wish to provide a value wherever that particular token is injected you should use use value so to understand that let's say that in our application we have let's go and create a file call let's say value dot this and in the value dot TS what I'm saying here I'm just creating a injection or token so we'll say export cost and let's say this is an API key you want to provide this a peek API key as a value wherever it is injected or in in almost all case throughout the application so here we're saying that hey export constant API key and this is going to be a new injection token so here I have taken new injection so here first import this we will say that import injection token and we want to inject import it from angular course so here we imported this injection token and you can use this here as injection token and that is of type string all right and then here you need to provide what is the purpose of this injection token so here we are saying that API key for app so API key for app so here you created an injection token called API key and we are going to use it to pass the value all right so here it is now to use that let's go to app dot component or TS let us say if you want to use it up in the component so for that in the child one component I want to use that so what I'm going to do in child 1 component or TS right here we'll say that after log service that hey inject API key as a so here you injected this API key alright and all right and to use that what I'm going to do here let's say that I have a API key as any here in the application and then we are saying that ok this daughter API key is equal to this a which you passed and here in the child 1 component what we can do let's go to the H the template of child 1 component and here let's say that after the mass is just display that API keys which is API key dot whatever we will pass from there will try to display that all right so now we have injected this API key but we have not provided it so to provide it let's go to the module level and in the model or we can say that here right here provide API huge we just created and whenever this key is provided whenever these kids provided use a value and here is that value and here we can say that use value in that you can pass whatever you want to pass let's say that we are saying that API key is one two three four five six all right so here you are passing this API key and then you can right here you are if you print this you can print this console dot log this dot API key and that should be available to you right here and that is being passed as a value not as an object and also here you can say API key dot and from there if you look at there we are passing this API key so that should be API key dot API key or because that's an object and the property all right so here we are compiling their application compiled successfully right here and you see that you have one two three four six being passed so use value is actually used to pass a value an injective value wherever you need it here we injected in that child one component you can go and inject it anywhere you want so let's say that you want to inject it in a child too you can you can inject it in the child too as well so let's go to child to that component Ortiz and right here we can just modify this constructor and then here we can say API key is of type in all right so here in that child to also now that got injected and it says that this API key is not available so say that API key from the value all right and then inject it from angular core all right so here we are it's compiled successfully and now in the father child to also you see that you are getting the output API key for child 1 also you are getting the so in this manner you can use use value to inject a value in the application so we learned about use class we learned about UJ listing we learned about use value fourth option is huge Factory huge Factory allows you to return an object like which class objects should be created from a function the function factory function can have a business logic and on basis of that angular would decide whether it has to create object of log service or whether it has to create object of update a log service if you seen huge class and huge existing if you are directly passing it and object of that particular class is getting created so here what I can do I can go and create a factory meter so let's say that I have a value called here late config value and that is set to nine it can come from a application level JSON file or anywhere but here just for the demo purpose I am hard-coding that then I have a function where get log object and what this function does this function have a very simple business logic which says that hey if this conflict value is equal to equal to nine then please return me object of log service all right otherwise return me object of updated log service so what this Factory does that it's it returns object of log service if conflict value is equal to nine he returns object of updated log service if it is not equal to nine so here it is let's say that by default it is equal to 19 so we are expecting that value of updated lock service should return and what we will do wherever this log service is provided what we want we don't want to use this huge class now we want to use either log service or of detail log service on basis of the some business logic so instead of use class we would say that use Factory and here you need to pass name of the factory which in this case get log or so here now you see that for the lock service it will call this factory function and right now to return us object of update a lock service and that object would be used for updated lock service as well because that is using huge existing and token is lock service so on running you see that here you are getting holo updated child on holo updated child 2 and child 3 because updated lock service has been called from the factory method if you go and modify this let's say that we modify this to 9 now what would happen that this function would return us object of lock service and that should get reflected everywhere and here you see that you are getting output from lock service not from the updated lock service so huge factory allows you to create an object depending on our business logic what you see shear use value allows you to inject of value and huge class allows you to create an object and use existing allows you to use existing object of a already existing token so these are the purpose of these 4 providers in angular so far we are working with a single module all these services concepts of provider injectors for root providing is equal to root or use factory use class UJ listing we are working with a single model how when we create a service works with multiple models so for example we created a service here and that services provided in application module level then how it would be provided inside the feature model how it would be provided inside the model which is eagerly loaded how it is it would be provided inside the model which is lazy loaded so let's see that how that works so to do that what I'm going to do here I am going to add a model in our application and we'll say in GG m and let's say that model name is feature so adding a new model in the application once that is added say in GCC and then call that component as of teacher as well and say that module is equal to future so to create a model called a component called feature and add it inside feature model here it is added and let's run this all right and then in the application you can see that we should have here a feature model got created so inside this we have a feature model in the future model here we have a future component created so go to definition here we have a feature component future company is going to have going to be exactly like any child component where we were using that so let's see this let us take this API key and put it inside the feature that component dot T is alright let's say that we don't want this to inject the value just to keep it simple or we'll work on work on a lock service and here it is and we'll saying that import lock service from logged service and then this is not needed let's get rid of this and here this dot masses so we need a mass is of type history all right and the end lock service and here it is it is feature modeled alright and let's go to app dot model dot T is inside AB dot module dot T is what I'm going to do just to keep it simple let's say that use class and in that use log service alright so here it is we are saying that for log star which token for ability lock service token huge class lock service and and here ujz sting log star which token all right and then in the future component just to its HTML here we can say that okay display the masses all right last but not least what we need to do we need to take this F feature and we need to use that so we can use that inside app component and right here in the app component or HTML just after child 3 let's add feature as well and also one thing you need to do is take this feature component and go to feature dot model dot is and make sure that you have exported that as well so here we'll say export and we need to export this feature component alright so here we have added a module which is eagerly loading loaded and we are using the lock service which is provided at the application module label right here and using that using that in the application so here it looks let's see that if it is compiled successfully it's is that error occurs on a template of this so let's say yes and again try to run this if you are doing any mistake one thing you probably we need to do is in the app dot module dot T is we need to make sure that whether feature model is imported or not so we will go here and import that so say import that feature module and we got to import that here and this feature module is imported at the application level alright so here it is imported and let's see that whether it's compiled successfully and our app is compiled successfully and then here run this and we should see that hollow feature model hallo charlie hello child - you are getting X period output and right here in the module if we go and change from this log service to update a log service you will find that is available in the future module in the future module as well and here you are getting this one thing you should focus here in the console that only one object is being created so if you are injecting service at the application level and that service is being used in the future models which are eagerly a loaded which are loaded not in the lazy loaded manner here you see that the same object being used in the application and all the features module now let us see that how we can work with lazy loaded model if you do not understand what is a lazy loaded model means these future models we just added and working on what angular will do or anger will make this model part of the application from the beginning because this model is eagerly loaded if a model is lately loaded it means that that model would be downloaded into the browser only user is using that or and when user is using that particular model so to understand it let's go back here and first add few models in a lazy loaded manner so what I'm going to do first adding a model here called customers it has its own routes and it is added to AB dot module all right so here we added one module once that is added then go ahead and add one more model called orders so here we are adding one more model called orders this is the angular CLI command to create models alright so once we added that here you can see in the application let us go to the application you see that you have orders module added in the orders module you have or a component or TAS you have auto routing module dot T's and order of routing order routing module RTS has information about that which components should be loaded to the default of this module in the same way here it is it is exporting and doing all those things same way you might find that customers model being added it has the its own route module and all that since the other child model here it is for child is being used for the customers and for child is being used for orders as well now if you go to app routing mattias here you see that information being added for those two lazily loaded up paths so here we are saying that okay so you see that here angular has added it for you it says that if base URL slash customers then load children and this is the syntax to create a lazy loaded module load a model in a lazy loaded manner say load children and then use the import statement to go to that part and then it is successfully if that promises success that is loading that model same for the others model here we can go and add one default path to the application that if none matches then it should go to a default path so here I am and then I'll just say that okay at a default path for the full so if none of these URL matches you should go to a default differed route so here you see that we have added two models and those models are loaded in a lazy loaded manner inside the app model now to do that what let's what let us do let us go let us go to app module and first add a few buttons and then on that button we will try to try to unload these models so to that let's go to app that component or HTML and right here in let's get rid of this scene yet okay let it be there and here I'm adding two buttons so here we are having two buttons which says that three buttons actually that if customers button is clicked then base URL says customers should be loaded if orders button is clicked in base you are is less orders should be loaded otherwise this on home it would go to the default route so here we added that and we want to load that particular models and for that we need to add a router outlets let's go and add that router outlet so what I have done right now is has nothing to do with dependency injection services just we are trying to load a module in a little man so here it is let's go and run the application so here I am and I'll say that in Jesus or I just ran few commands and here on the button obvious we'll just load that models component inside this router outlet and every module if you go here has a default component so go to a prod in dot module tortillas and here you see that if path is default then it it will load orders component and same you will find the configuration for customers as well here you can see that alright so here compiled successfully and run the application so here we are running the application let's go to first console everything is working as expected so let's go to first Network and then again refresh it so here you see that are many files being downloaded here now a please notice here you have runtime tortillas polyfill dodgiest also J's and all now when I click on this customers you see then this customer model dodgy has got downloaded that URL is changed on the top and here you get output customer works when I click on orders then this orders model Dodge's is downloaded and you are released changed so it is these models are downloaded when you are using that and this is called a lazy loaded models so now we saw that we are able to lazy load customer's model and others model now let us see that how we can use login service inside these models so here first modify the lock service what I'm going to do in log service that if you remember we had a API T and then we are providing that here in the app dot model dot TS which has a api key and the name of the model so the idea is we are going to have different API key for different models at least four different lazy loaded models so here for API e which is available for app model has this value and model name is app so first what we are going to do the log service first inject that API key here and we can inject that using inject as you did in the in the components and here you can say inject this API key all right I can give any name and giving it name as API key and let's say that this function has one this service has one function called gate API T and this knowledge should be fine here we injected this alright and then we are returning this what I had done in the child component I am making call to the apt-get API key function which we just added to lock service and then setting this value to this API key and then on the HTML we are displaying that API key and module name so right now the output are stood more or look like this here you have key and module name app all right now what if here we want to have the same for different model so let's go here in this and just copy this from here and let's go to this RS model in the order model we have this order odd component or HTML we'll just put it here here a message string lock service saying log-dog service and then let's call this as orders and it has gate api key and you are and we need to display that and we can display that right from here so take this from here and go to orders dot component dot HTML and just paste that code so here we are pasted code that is for orders and the same way I take this and go to our other lazy loaded model 2 as a customer here in the in the customer will go to customer module and first so it paste it here and then again take this alright and then from child component we can take this from here and for customers also in the t's we can put it here alright so or nothing fancy it is both lazy loaded customers and log services making call to the log service API which is available provided at the application level and here we can call this as customer and and let's see that what output we are getting first see that is compiled successfully and we are here getting for this module name app and when we click on customers you see that a customer is now displayed and that also has the same key and module name available of course because we are passing the same for the API key token and for the orders also when we click here it has changed to holo orders and it has the same key 1 2 3 4 6 and app now this is good if this is our requirement and you see that even if it is a it is a lazy loaded model you don't have to do anything extra for that now let us assume that for a customer we want to pass different value and for orders we want to pass different value what we will do so of course let's go here in our application first go to the model here and in the model we will say that let us take this provide API key and you would say that I'll pass it at the level of will pass it at the level off from in the model so here we will go let's say that in the in the model up for order and here we can say providers and then we can do this so here we say that hey provide that API key and here we say that this key is nine and this is an order model so pass that as order all right so we can do this very much and in the same way we can go to a customer model and here also we can say that providers and we can pass that and share this value and let's say this value is nine eight seven six five four three two one and we are inside the customers model so this is a customer here the model name is customers now let's see that what is happening so here we are and back to application everything looks good so so here it is coming one two three four five six model M one and one object is being created as you see here then when I click on customers you see that now still this customer also had this same model name past app the orders also has the same model name past app now the one step left is it is still using the same or log service so for that what we can do we can come here and say that use this API key use value and also besides this please use lock service here we are saying that use lock service and then in the in the same way we go to order models here and we pass that log service sorry to create a new instance of log service and then it will pass this in the newly clear instance for this particular model all right so here we are and let's go back to here it's one two three four five six app one object created when you click on customers here you see that for the customers now we are getting different different value but a new object created for lock service now you have two objects one for the whole application one for the customer's model when you click on orders again the third object got created and this objet is not being used and you are getting this order I can go to customers the same second object would be used for the customers module go to orders the third object will be used for the orders module and if you go to home the same first object would be used for the whole application and up and the newly-created and the models which are eagerly loaded alright so this is actually we are able to achieve what we wanted to achieve you see that we are able to see that we are able to provide that and everything is working fine and what we just done we just injected the lock service here now the problem with this approach is and this is a way we used to do before angular 9 and the problem with this approach is this lock service is now not three shakable even if in this order model this lock service is not used angular is going to create object of this keep in mind since you have passed into the providers as we discussed earlier this is not a tree say cable so to make it 30 second what we need to do it will make these locks that is not to stress a cable and to make it resectable what we will do we have to first remove it from the providers of everywhere here also we remove it from the providers but if we do that and in the app module also we need to get rid of this from here so what I'm going to do I am going to get rid of I'll say that for updated lock service use updated lock service and Here I am going to get rid of this provide because we want to make it as a tree shakable object recyclable a service for that we got to come back to this lock service dot TS and here if you go to the beginning of our lecture today and here we would have to say that provide in at the root level if we provide in at the root level then see what is happening it says that is not here it should we are passing at the root level it should give us let's go and try to run it again so here we are running running this application again all right so here we are saying that hey provide in is equal to equal to root all right and let us wait it for successfully compiled all right so here it is compiled it's go back to our application again and run this so here they are getting to module name app when we click on customers you see that it be providing at the root again you are getting the same configuration because there is only single an object of that is created as we discussed earlier and it will not create a new object however we are requirement is to get separate value for separate more lazy loaded models here not the same value and you can do that by changing this value from root to any if you change this to any what would happen angular will create new object for each lazy loaded models and plus the application model so it will create three object here and we are back here and let's run this application again you see one object god created you are getting one two three four six customers you are getting here customers another object got created and orders third object got created and if you use any it is three say cable so you can achieve that using provide also but that is not recyclable if you use it any it is to say cable so what any provide in any of enables us that it will create separate object for all the lazy loaded modules and a single object would be shared between the application and all the eagerly awaiting eagerly loaded model so here so in this video we almost learnt everything we need to know about services and dependency injection in angular I hope after watching these 70 minutes of video now you are well informed about what is the purpose of route what is the purpose of any when to use use class use value use existing huge factory how to work with lazy loaded module and services etc once again thank you so much for watching this video
Info
Channel: Geek 97
Views: 8,848
Rating: undefined out of 5
Keywords: Angular, geek97, ngIndia, useClass, useValue, Angular 9, useFactory, any, root, singelton service
Id: K-hUBv2TZ0w
Channel Id: undefined
Length: 75min 29sec (4529 seconds)
Published: Sat May 23 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.