ocombe / ocLazyLoad

Lazy load modules & components in AngularJS
https://oclazyload.readme.io
MIT License
2.63k stars 510 forks source link

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

Open tjsums opened 7 years ago

tjsums commented 7 years ago

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

batista commented 7 years ago

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...

alanwright commented 7 years ago

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.

xiaokyo commented 3 years ago

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