#Angular Router Guards Pt.1: CanActivate vs CanActivateChild (2021)

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
Hi everyone! My name is Dmytro Mezhenskyi  and in this video we will try to figure out   what the difference between guard CanActivate and  CanActivateChild in Angular Router. We will see   different use cases and in the very end of the  video i will show you one interesting pattern   so stay here and before we start i would like to  remind you that i have a couple of video courses   first one about Graphql engine called Hasura which  allows you to turn your database into real-time   and performant Graphql backend and the second  one about the angular material theming in this   workshop you will figure out how to properly  theme your components your application and   things like that the links will be in the video  description check this out and let's move forward   okay let's have a look at this application i  prepared for this tutorial and you can see that we   have the toolbar with two menu items and we have  some text which indicates that we are on the home   page and we can jump also to admin page which is  secured admin area and this secured admin area has   a few actions like add user and add product and if  i click on this button add user i see the form in   order to add some user and if i click add product  i will see the appropriate form for product   so as you can see very simple application  and now let's have a look at the source code   as you can see here this is the very simple  angular app inside the app component we have the   map toolbar and we also have the main tech and  here inside i use a router outlet in order to   render components which associated with some  certain uh road and um yeah nothing interesting   here this is just a simple um app component let's  have a look at the app rolling uh how it looks   right now and you can see that we have the empty  path where we render home component this is   what you have seen right there and we have  a bit more sophisticated route which is   admin and we have like on the road admin we  render the welcome component which is also very   very simple we will have a look it in a second  and it has two children add user and add product   now let's go to the admin model and like check  one by one how it looks like so we start from   the welcome component here when we navigate to  the admin we see this component which is which   represents our welcome component and inside ts  file we have nothing but here we have another   our router outlet where we're going to render  child roles and it's associated components right   here and this is just a section with actions and  some h1 header so this is basically this part what   you can see right here and then if we navigate  to add user uh we will see that it has just a   simple form inside ts file we have also very basic  form builder and very similar thing we have done   for also add product component uh yeah this is  how it looks like and it's worth to mention that   we have also out where leaves only one service  and this is authentication service so far it has   um like mocked functionality we don't go to  the server to check user authentication or we   don't check any jwt tokens whatever it's just  smoked it's just for this particular example   so i hope everything is clear for  now and as you may notice that   we have access to admin for anyone we don't have  any custom logic which protects our route from   unauthorized users and we're going to fix it and  we will fix it with the connectivity card which   you most probably all know but for those who is  not aware it might be useful so let's go to the   uh code and i'm going to create the can activate  uh road guard first and i will be using the   extension you're always asking me how cold this  extension it's called nx console which allows you   to generate um components and this is how it  uh looks like an x console once you installed   you will be able to click on some folder whatever  and you will get this ng generate ui and here you   can pick that you want to generate guard so let's  do it and i will name it like authentication   then we have to pick which one guard guard  type it is so i will pick can activate   the rest we will check maybe in some next videos  uh but for now we care only about can activate   then i say that it should be rendered under the  auth folder and then i take skip tests because   i don't need tests for this particular case  because it's just example and then i just click   run and it should generate authentication guard  and let's have a look inside what do we have so   as you can see that this is just uh service  yeah you can see injectable provided in root   and the one difference is that it implements  can activate it implements can activate because   this service which we're going to use are the  authentication card should always have this can   activate method and implements kind of forces us  to implement some logic there here you can see   that it takes two parameters this can activate  method you get activated road snapshot and   you get the rotors the whole rotor state snapshot  and you should return it the observable of boolean   or url tree if you want to redirect redirect user  to some another road or you can also return the   promise with the same like boolean or url tree or  it can be just boolean or it can be just oral tree   so far it returns true so always everyone can  access the the road which is protected with this   authentication guard but let's make it a little  bit smarter so i'm going to inject uh inside the   constructor my auth service so i will call  it auth here we go and here i will say that   please check is logged in and then i will use pipe  and inside pipe i will use map and i say that if   so i will get i hear the result or what return of  this is logged in so i will get some boolean and i   will name it like if is authenticated or let's say  is logged in right and i either return logged in   if it's true or if it's not true i want to return  url 3 in order to redirect user to some particular   role let's say on the home page and in order to  build this url 3 i need to inject also router   here we go and here i say that please uh create  oral 3 3 for empty road so it means for home page   right and this is what we're going to  return but we have to also connect this   authentication guard with some particular road  correct and in order to do this we go to our app   routing and i say that the admin road should be  activated so i'm using this keyword can activate   for this and inside the array i say that it should  put this guard so oops i forgot comma here so   yeah now if we attach the authentication guard to  this road it will check first uh our can activate   method if it returns true then it instantiate  this component we defined here otherwise   uh either happens nothing if we return false  or it will be red we will be redirected to the   url we defined inside world world tree  and if we save it let me check if i say   yeah looks fine and you can see that now it works  fine because we return um hard coded true value   now let's try to return false just to emulate that  user was logged out or something like this and you   can see that we were immediately redirected to  their home page i tried to navigate to the admin   but it doesn't work because we protected the  admin so can activate takes the routing you are   applying to and everything all children  which calls after this admin road they   will be protected by this authentication guard  okay so let's maybe revert it back to true and let's uh console lock something here inside  our can activate so i say that like console.log   like i'm checking out okay and now let's try  to go back to our web app and open the console   here we go i will zoom it in and see  the interesting thing when we reload   we see that i'm checking out was executed that's  fine however if we go to add user and then we   go to the add product we see that it was not  involved as well but sometimes we would need   to have some additional check every time we  activate some child role as example we have   different rights for admin someone has  right permissions someone has only read   permissions and every time we activate a child  road we want to check permissions all right and   you can also implement this by using  connectivate and let's do it so i will   again use ng generate and we say that we  need guard and i will name it per missions and we also like do it like can activate okay  here we go let me just delete the test file and i will move it next to our authentication  okay and here in our service let's add maybe   some method like has permissions okay and it  returns observable of true as example for now good and inside our permission we would  do something similar what we have done for   our authentication guard so i inject  service and then i would need to check   if this house has permissions then we can like  enter this road and we can save it actually   and copy this or i will remove also on this route  because it's we are not using them and then i   will go to my app routing and i have to like can  activate and call permission card against every   roll so i can copy this here as well and i just  paste it and we have to import this of course   here we go so if we reload and then i  navigate between we have to add also   console.log here in order to see if  it was executed so console log like   i'm checking permissions okay and now  you see that we activated admins so   our out guard was involved and then we also  do a permissions check for add user component   and if we go to add product you see that  permission check again has been involved right   and every time we try to activate some certain uh  road or component that can activate will be called   also for child but here we have only two children  yeah but imagine the real live app has tons of   child components you can have i don't  know dozens or even hundreds uh child   children's four year old and you have to add  manually this permission guard for every child and   this is very error prone because you just simply  can forget to edit and to not underestimate it   really it sometimes happens  even with experienced developers   so uh the better way to handle this thing would  be exactly can activate children and the thing you   have to do is just slightly modify our permissions  guard and instead of implementing can activate   interface you have to implement can  activate child and here you have to just implement slightly different interface  so it called connectivate child and   basically we can copy everything from can activate  here and paste it in place of this throw error and   you can see this is very similar to what we had  with connective 8 we have just a child rolled so   this is the road which we're going to activate and  the state of the rotor state of the rotor state so   we are not going to use it so i will remove it  but just to let you know that we have such um   such arguments good uh don't we  have any errors looks like no   and now we have i use this permission guard in  our routing but we don't use this can activate   anymore we use can activate child and here  inside array i will provide our permission   guard and now i don't need it anymore for my  my children and if i save it we should see   the same behavior i will go to admin and navigate  between childs on and every time i activate child   this permission card was executed so once  you add some new child to it you should not   care about providing the permission guard  anymore because by default everything under   this road will be protected with a permission  guard and now as a small bonus let me show you   the pattern called componentlessroad and it  looks like this so we we just temporarily copy   this roads here and we introduce the new road  and the path for this road will be empty string   and here we don't define any component that's  why it called componentless but we called   here children and already here inside the children  we paste the roads we copied before so it looks   like this right now so we have kind of middleware  road which is which has empty string and   in our case it me it like it doesn't change  anything for us because uh it still will be   mapped as admin add user because here is empty  string so yeah we do admin then technically should   be some rolled but because it's empty they will be  mapped the next one add user so if we save it like   this nothing has been changed everything works uh  fine but what the benefit then from this pattern   well getting back to permissions you can see that  we have add users and add product which means that   this is something which is allowed to do only  for admins who has write permissions and you can   see how we structured our route so we have admin  and there it goes add user and then we have add   product yeah they kind of on the same level the  child of admin wrote but what if we want to have   road called list as example which is  also on the same level with the admin   but we want to have this road available for any  kind of admins so without this pattern if we would   revert it we would need to add this list next to  add product and add user and our permissions guard   which check this strict rules would apply also  for this new router which we could name list   you know what i mean but we don't want to apply  this permission guard to this particular road   we don't want to have it that's why we're using  this middleware road in order to group these two   roads under the one guard and in our case it will  be can activate child permissions guard yeah so we protect everything which is child for  this pass and technically to admin   with this permission guard but if we  want to introduce on the same level   the another component which should be  accessible without any check we can do it by   adding it next to this middleware role so  here somewhere i will introduce the path   with empty string or not empty  string i will call it list because i want to have admin slash  list and then render some component   which we have to create so let's maybe where  we're going to create under the admin i will   generate or let's generate  material table so i call it list i declared under admin okay looks good i run it so we can see that the list  was generated so now we can go to app routing and import the list component  here we go and now we can see that ah we have   to add the action to this list right so okay  here is our actions so i will duplicate it   and then let's say show list i will name it like  this and here the router link will lead to list   here we go now we see the new action you can see  that permission checks happen to end user and add   product which are scoped by our componentless  compo rotor sorry right these guys but   if we navigate to the list you will see that this  check was not executed anymore however we have it   on the same level with the add product and add  user so this is where this componentless pattern   componentless router pattern might be useful all  right guys that was it thank you for attention i   hope you enjoyed it and don't forget that this is  just a first part of a video series about angular   router guards in next video we'll have a look at  the rest of them and if you like what i'm doing   please share this video with your colleagues  hit thumbs up and of course don't forget to   leave your feedback in the comment section and i  wish you productive week and see you in two weeks
Info
Channel: Decoded Frontend
Views: 28,032
Rating: undefined out of 5
Keywords: angular router guards, angular guard canactivate vs canactivatechild, angular router canactivate, angular auth guard canactivate, canactivatechild angular, angular can activate guard, angular canactivate, canactivatechild angular 8, angular guards tutorial, angular guard authentication, Angular routing, angular 12
Id: NxidP4I9EHE
Channel Id: undefined
Length: 24min 51sec (1491 seconds)
Published: Tue Jun 22 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.