5

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?

HDJEMAI
  • 9,436
  • 46
  • 67
  • 93
Thomas Segato
  • 4,567
  • 11
  • 55
  • 104

4 Answers4

7

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.

ygorazevedo
  • 487
  • 1
  • 4
  • 14
2

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.

Suresh Kumar Ariya
  • 9,516
  • 1
  • 18
  • 27
1

This issue is also occurs when you have changed base href value

<base href="/"> to Something else

in index.html

Basavaraj
  • 11
  • 1
0

It seems that it is a URL Re-write issue. If you have iis server then you need to put web.config file in the server and add logic for url rewrite. you can find it in the angular.io

If you have apache then you need to write you have to add [.htaccess][2]

[2]: Deploy Angular 2 to Apache Server file.

saumil_
  • 304
  • 2
  • 11