question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Use a service from a manual loaded module using Angular 8

See original GitHub issue

🐞 bug report

Load programmatically module and use its service whithout using SystemJsNgModuleLoader.

Description

Using Angular 7 I can load programmatically a module (defined in angular.json “lazyModules” section) and use its service. How I can achieve the same functionality without using deprecated SystemJsNgModuleLoader?

LoaderComponent

@Component({
  ....
  providers: [SystemJsNgModuleLoader]
})
export class LoaderComponent {
  constructor(loader: SystemJsNgModuleLoader, injector: Injector) {}

load() {
this.loader.load('src/app/evaluate-process/evaluate-process.module#EvaluateProcessModule')
      .then((factory: NgModuleFactory<any>) => {
          const moduleRef = factory.create(this.injector);
        const eps: any = moduleRef.injector.get((<any>factory.moduleType).eps);

        eps.startMyFunction();
      });
}

EvaluateProcessModule

@NgModule({
 providers: [EvaluationProcessService]
})
export class EvaluateProcessModule {
  static eps = EvaluationProcessService;
}

🌍 Your Environment

Angular Version: 8.1.3

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Comments:24 (7 by maintainers)

github_iconTop GitHub Comments

1reaction
mikezkscommented, Aug 1, 2019

The following aspects need to be respected so that NGC can find your dynamic import request correctly:

  • You need to use the loadChildren syntax: { loadChildren: () => import('../my-demo/my-demo.module').then(m => m.MyDemoModule) }
  • Using dynamic parts inside a literal for the path or module does not work
  • Using this statement inline does not work for me, but you can use a reference to this definition
  • Using it as class property does not work
  • Using an exported const works for me
  • It is possible to nest this syntax as shown above, so that you can use several definitions which are accessible by property name
  • This way you can use a string value to dynamically load a certain module: lazyModules['myDemo'].loadChildren()
1reaction
mikezkscommented, Jul 31, 2019

@mlc-mlapis , i found the a working solution now:

export const lazyModules = {
    myDemo: {
        loadChildren: () => import('../my-demo/my-demo.module').then(m => m.MyDemoModule)
    }
};

class Loader {
    load() {
        return lazyModules['myDemo'].loadChildren()
            .then(moduleOrFactory => {
                if (moduleOrFactory instanceof NgModuleFactory) {
                    return moduleOrFactory;
                } else {
                    return this.compiler.compileModuleAsync(moduleOrFactory);
                }
            })
            .then(factory => {
                this.moduleRef = factory.create(this.injector).instance as unknown as NgModuleRef<any>;
            });
    }
}

more on this later.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Manually Lazy Load Modules And Components In Angular
The loadLazyModules method simulates a backend request. After a successful request, a module is registered using the import(...) syntax. If you now run...
Read more >
Add services - Angular
This tutorial creates a HeroService that all application classes can use to get heroes. ... Inject in HeroService , which uses the service...
Read more >
Lazy Loading Modules & Preloading Strategy in Angular 8
To use lazy loading, first, you need to create some feature modules. Feature modules are NgModules created for the purpose of code organization....
Read more >
How to auto run a service from a module when it's imported in ...
You can use the APP_INITIALIZER injection token to run initialization code before any of your other application code runs. APP_INITIALIZER is ...
Read more >
Manually Lazy Load an Angular Module with ViewEngine and ...
By simply specifying a route configuration with the import(...) , Angular will take care of splitting that corresponding module out into a ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found