Angular 2 Routing : 404 page not found on refresh

Dhanraj Acharya
wineofbits
Published in
2 min readJun 28, 2018

If you’re new to angular then you will encounter a problem like refreshing the page gives 404 Page not found error. Because angular applications run in their own sandbox, URL changes happen using simple js only. so to a user, it might seem like they’re visiting different application but in reality, it’s just single page showing different views. well, that’s what angular is for; single page application. this problem also blocks web crawlers as there is no content on the given link. everything is dynamic. so your website might not be crawled properly resulting in less presence in the search engines.

Angular knows about this problem and gives solution by using Angular Universal. but if you want a quick solution then you can use below two methods that add a ‘#’ in front of every route so that first index file (web app) is loaded and it shows processes the rest of the URL according to the routing rules.

Method — 1

In app.module.ts:

  • Add imports:
import { HashLocationStrategy, LocationStrategy } from '@angular/common';
  • And in NgMoudle provider, add:
{provide: LocationStrategy, useClass: HashLocationStrategy}

Example (app.module.ts):

import { NgModule }       from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { HashLocationStrategy, LocationStrategy } from '@angular/common';
@NgModule({
declarations: [AppComponent],
imports: [BrowserModule],
providers: [{provide: LocationStrategy, useClass: HashLocationStrategy}],
bootstrap: [AppComponent],
})
export class AppModule {}

Method — 2

Use RouterModule.forRoot with the {useHash: true} argument.

Example:(from angular docs) (app-routing.module.ts)

import { NgModule } from '@angular/core';
...
const routes: Routes = [//routes in here];@NgModule({
imports: [
BrowserModule,
FormsModule,
RouterModule.forRoot(routes, { useHash: true })
],
bootstrap: [AppComponent]
})
export class AppModule { }

Conclusion

And that’s it! Did this work for you? Please leave any questions and comments below!

Thank you for reading!

If you found this article helpful, 👏👏👏.

--

--

Dhanraj Acharya
wineofbits

Full Stack Developer. I love experimenting with new tools and tech. More @ https://drex44.github.io If you can’t read any story due to the WALL then DM me @Twtr