Doctor Strange
Doctor Strange

Reputation: 209

Angular lazy loading not working with direct url

I'm running .net Core + webpack 3 + Angular 4.

My lazy loading works just fine when used inside the app, Like thru the navbar, But fails when I try to access the lazy loaded url directly.

fail: Microsoft.AspNetCore.NodeServices[0]
      ERROR { Error: Uncaught (in promise): Error: Cannot find module './components/members/members.module.ngfactory'.
      Error: Cannot find module './components/members/members.module.ngfactory'.
          at /root/myApp/bin/Release/netcoreapp2.0/publish/ClientApp/dist/vendor.js:35933:9
          at ZoneDelegate.module.exports.ZoneDelegate.invoke (/root/myApp/bin/Release/netcoreapp2.0/publish/ClientApp/dist/vendor.js:92811:26)
          at Object.onInvoke (/root/myApp/bin/Release/netcoreapp2.0/publish/ClientApp/dist/vendor.js:14833:33)
          at ZoneDelegate.module.exports.ZoneDelegate.invoke (/root/myApp/bin/Release/netcoreapp2.0/publish/ClientApp/dist/vendor.js:92810:32)
          at Zone.module.exports.Zone.run (/root/myApp/bin/Release/netcoreapp2.0/publish/ClientApp/dist/vendor.js:92561:43)
          at /root/myApp/bin/Release/netcoreapp2.0/publish/ClientApp/dist/vendor.js:93238:57
          at ZoneDelegate.module.exports.ZoneDelegate.invokeTask (/root/myApp/bin/Release/netcoreapp2.0/publish/ClientApp/dist/vendor.js:92844:31)
          at Object.onInvokeTask (/root/myApp/bin/Release/netcoreapp2.0/publish/ClientApp/dist/vendor.js:14824:33)
          at ZoneDelegate.module.exports.ZoneDelegate.invokeTask (/root/myApp/bin/Release/netcoreapp2.0/publish/ClientApp/dist/vendor.js:92843:36)
          at Zone.module.exports.Zone.runTask (/root/myApp/bin/Release/netcoreapp2.0/publish/ClientApp/dist/vendor.js:92611:47)

... Is there a known fix to this problem or a workaround so I could mimic the way the router works inside the app and 'redirect' the request to the lazy loaded model

Upvotes: 6

Views: 1732

Answers (1)

Michael Kang
Michael Kang

Reputation: 52837

Use the Hash location strategy:

RouterModule.forRoot([...], { useHash });

Why does this work?

In most web servers, including IIS, the part in front of the hash is treated as the path to the actual page on the server. But the route really only exists within the client-side application. The deep link will hit the server first, and of course the route doesn't exist, and so a 404 error appears. Using the # location strategy fixes that since the server ignores the part after the #, and so it resolves the page correctly from the server perspective. Angular does the rest to bring you to the right page.

You need to tell the web server that deep links into a SPA is ok. Here is a guide that looks pretty good: https://gingter.org/2017/03/20/deep-link-angular-spa-iis/

Upvotes: 1

Related Questions