I have an Angular 6 application with a component called assets. When I navigate to the component through routerLinks, the page load and shows data as expected:
http://localhost:4200/assets/2
However if I refresh the page, or just load the link directly in a browser then a lot of my scripts fail to load:
GET http://localhost:4200/assets/runtime.js net::ERR_ABORTED 404 (Not Found)
Refused to execute script from '<URL>' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled.
GET http://localhost:4200/assets/polyfills.js net::ERR_ABORTED 404 (Not Found)
Do I need to do something in the router or what's causing this?
You can navigate one to another page in Angular in Two ways. (both are same at wrapper level but the implementation from our side bit diff so.) routerLink directive gives you absolute path match like navigateByUrl() of Router class.
Why do we need Lazy Loading in Angular 4? Lazy loading is a technique in Angular that allows you to load JavaScript components asynchronously when a specific route is activated. It improves the speed of the application load time by splitting the application into several bundles.
Component: This property refers to the angular component that should instantiate for this route. Children: This property defines nested routes, and angular would load them upfront. LoadChildren: It is also used to define nested routes, but Angular Router would lazily load them. You see the advantage here.
Enable hash location in your route module. It should look something like the follow.
const routes: Routes = [
{ path: '', component: MyComponent },
{ path: 'my-other', component: MyOtherComponent }
];
@NgModule({
exports: [ RouterModule ],
imports: [ RouterModule.forRoot(routes, {useHash: true}) ]
})
export class MyRoutingModule { }
After that Angular will be able to process refreshing.
This is because, Angular router by default uses PathLocationStrategy.
http://localhost:4200/assets/2. When you refresh the browser, you need to redirect to home page (index.html) and this should be handled in server side router redirect settings.
You can also try HashLocationStrategy i.e it will add router path with '#'. http://localhost:4200/#assets/2. If you follow this, you can handle page refresh. But we need to make sure the page state is available in all the modules including Lazy Loaded Modules.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With