ocLazyLoad icon indicating copy to clipboard operation
ocLazyLoad copied to clipboard

How to lazy load 'component' in angular 1.5/1.6?

Open tjsums opened this issue 7 years ago • 3 comments

From angualar 1.5,a new feather 'component' is published. But,in ui-router ,how to lazy load the 'component'?

tjsums avatar Feb 26 '17 15:02 tjsums

I assume this question would be better in SO (and spellchecked).

Nevertheless, the following is how I've implemented in Angular 1.5:


In my route (this case /lazyloaded-route) resolver, i trigger the component loading from a loading service that encapsulates ocLazyLoader and adds some more behavior (in my specific case, I use it for only loading the components if the user has permissions to do so).

/* routes.js */
angular
.module('MyApp')
.config(['$stateProvider', 
function($stateProvider) {
  $stateProvider.state('lazyloaded-route', {
    url: '/lazyloaded-route',
    template: '<lazyloaded-component></lazyloaded-component>',
    resolve: {
      loadFiles: ['$injector', function($injector) {
        return $injector.get('lazyLoadingService').loadFiles();
      }]
    }
  });
}
/* lazy-loading.service.js */
angular
.module('MyApp')
.factory('lazyLoadingService', lazyLoadingService);

lazyLoadingService.$inject = ['$ocLazyLoad'];

function lazyLoadingService($ocLazyLoad) {
  var _filesLoaded = false;
  var _loadingFilesPromise;

  return {
    loadFiles: loadFiles
  }; 

  ////////////
  
  function loadFiles() {
    if (!_filesLoaded && !_loadingFilesPromise) { //only trigger the loading once
      _loadingFilesPromise = $ocLazyLoad
        .load(['/lazyloaded.component.js', '/lazyloaded.component.css'])
        .then(function() {
          _filesLoaded = true;
          // doStuffAfterFilesLoaded();
        });
    }
    return _loadingFilesPromise;
  }
}

hope this helps...

batista avatar Mar 01 '17 14:03 batista

I think it's important to note that lazy loading is done at the module level. Your component will be registered on a module, then you'll lazy load the module as @batista outlined above.

alanwright avatar Mar 10 '17 02:03 alanwright

I think it's important to note that lazy loading is done at the module level. Your component will be registered on a module, then you'll lazy load the module as @batista outlined above.

thanks, work for me

xiaokyo avatar Jul 20 '21 05:07 xiaokyo