Angular Routes: Redirect to blank page when fake url entered

I’m trying to develop a PWA and I’ve run into a potential problem with my angular route redirect. I’m not using tabs, and my app-routing.module.ts Routes look like this:

const routes: Routes = [
  { path: 'home', loadChildren: './pages/home/home.module#HomePageModule' },
  { path: 'login', loadChildren: './pages/login/login.module#LoginPageModule' },
  { path: 'signup', loadChildren: './pages/signup/signup.module#SignupPageModule' },
  { path: '', redirectTo: 'home', pathMatch: 'full' }
];

The way I want the redirect to work is so that if I type any fake/bogus information into the URL path then the system would redirect the path to home (and therefore load the home page content). For example, if I am currently on the http://localhost:8100/login page and then I manually edit the URL to read http://localhost:8100/fakenews, I would expect the angular router to recognise that this is not a valid route and re-direct me to http://localhost:8100, which would subsequently re-direct me to http://localhost:8100/home and display the home page to me.

The BAD news: When I enter http://localhost:8100/fakenews, I am re-directed to http://localhost:8100 however I am not subsequently redirected to http://localhost:8100/home. All I get presented with is a blank page and the following error in the console:

ERROR Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'fakenews'

Ionic_App

If I then hit refresh (F5) on this page then it does re-direct me to http://localhost:8100/home!!!

Is there any way I can handle this scenario in my routes to make sure that I am always re-directed to http://localhost:8100/home and never to http://localhost:8100 (the blank page)?

I found the answer on this page: https://angular.io/guide/router

I created a “wildcard” route to re-direct to the home page if the route is not defined:

{ path: '**', redirectTo: 'home', pathMatch: 'full' }
1 Like