CanLoad vs CanActivate for LazyLoading

自作多情 提交于 2021-02-07 11:57:13

问题


If I use lazy loading and have a guard defined for "CanLoad". Is "CanActivate" needed? As in is it possible for a module to be validly loaded but then the user does something which invalidates the "CanLoad" but since it is loaded the user can gets past the CanLoad.


回答1:


CanActivate is not needed for lazy loading if you already implemented CanLoad.

You may still want to replace the CanLoad with CanActivate if you need to check for unauthorized access.

This is what the NG2 doc says

The CanLoad guard blocks loading of feature module assets until authorized to do so. If you want to both preload a module and guard against unauthorized access, use the CanActivate guard instead.

See https://angular.io/docs/ts/latest/guide/router.html#!#preload-canload)




回答2:


  • CanActivate - Decides if a route can be activated, this guard may not be the best way for feature modules that are lazy loaded, as this guard will always load the module in memory, even if the guard returned false which means user not authorized to access the route.
  • CanLoad - Decides if a module can be loaded lazily, Controls if a route can even be loaded. This becomes useful for feature modules that are lazy loaded. They won’t even load if the guard returns false.

This is a test i made on both guards with a feature module that is lazy loaded:

1. CanActivate Guard Test

you will notice at the bottom of Network page that it made 24 requests with size of 9.5 MB transferred finishing in 3.34 seconds and fully loaded in 3.47 seconds.

1. CanLoad Guard Test

here you will see the big difference when we used CanLoad Guard as browser made only 18 requests with size of 9.2 MB transferred finishing in 2.64 seconds and fully loaded 2.59 seconds.

CanLoad Guard never load the module data if user not authorized and that gives you more performance as the load time decreased almost 1 second and that is huge time in loading web pages, no doubt it depends on the module size.

Tip: if you want to make the test on your project make sure that Disable Cache checkbox in network tab is checked, it's marked in first image



来源:https://stackoverflow.com/questions/39664364/canload-vs-canactivate-for-lazyloading

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!