2

I am trying to lazy load a feature module from another server.I have managed to export the chunk of lazyloaded module from the node server.By referring to Solution: load independently compiled Webpack 2 bundles dynamically. On running it, browser successfully loads the script from the server, But fails to navigate to the new location and getting an error

ERROR TypeError: Cannot read property 'LazyModule' of undefined
    at eval (app.module.ts:14)
    at HTMLScriptElement.script.onload [as __zone_symbol__ON_PROPERTYload
(app.module.ts:58)

app.module

const appRoutes: Routes = [
  {
    path: 'Module1', loadChildren: () => new Promise((resolve, reject) => {
      loadPlugin('http://localhost:4000/chunk.js', (exports) => {
        console.log(exports);
        resolve(exports.LazyModule);
      });
    })
  }, 
  { path: '*', component: AppComponent }
];

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    RouterModule.forRoot(appRoutes),
    HttpClientModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }


function loadPlugin(pluginUri, mainCallback) {
  installMainCallback(pluginUri, mainCallback);
  loadPluginChunk(pluginUri,  mainCallback);
}
function installMainCallback(pluginUri, mainCallback) {
  var _pluginIdent = pluginIdent(pluginUri)
  window[_pluginIdent] = function (exports) {
    delete window[_pluginIdent]
    mainCallback(exports)
  }
}

function loadPluginChunk(pluginUri, callback) {
  return loadScript(pluginUri, callback)
}

function loadScript(url, callback) {
  var script = document.createElement('script')
  script.src = url
  script.onload = function () {
    document.head.removeChild(script)
    callback && callback()
  }
  document.head.appendChild(script)
}

function pluginIdent(pluginUri) {
  return '_' + pluginUri.replace(/\./g, '_')
}

By referring to the error log, I guess that the error is due to lazyloaded module is invoked nowhere. What should I return to LoadChildren to invoke it?

Thanveer
  • 31
  • 2
  • 8

0 Answers0