Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loading a page directly in Angular 6

Tags:

angular

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?

like image 965
Thomas Segato Avatar asked Sep 28 '18 12:09

Thomas Segato


People also ask

How do I navigate to another page in Angular 6?

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 we use lazy loading in Angular?

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.

What is LoadChildren in Angular?

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.


2 Answers

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.

like image 100
ygorazevedo Avatar answered Sep 21 '22 18:09

ygorazevedo


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.

like image 38
Suresh Kumar Ariya Avatar answered Sep 17 '22 18:09

Suresh Kumar Ariya