angularhttp-redirectroutescanactivateangular-activatedroute

How to redirect unknown routes to home route in Angular program?


I have a routes.ts file like below:

import { AuthGuardService as AuthGuard } from '../services/auth-guard.service';

export const routes:Routes = [
    {path : '' , redirectTo : '/home' , pathMatch : 'full'},
    {path: 'home' , component : HomeComponent},
    {path: 'users' , component : UsersComponent, canActivate: [AuthGuard]},

];

And an auth-guard.service.ts file like this:

export class AuthGuardService implements CanActivate {

  constructor(public auth: AuthService, public router: Router) {}
  canActivate(): boolean {
    if (!this.auth.isLoggedIn()) {
      this.router.navigate(['home']);
      return false;
    }
    return true;
  }
}

And it works well for known routes like users but when I try an unknown route like homeee it doesn't work properly and shows a page with header and footer and no content among. How can I redirect all unknown routes to home component?

Also I like to know is this a good way for what I like to do or not? (I like only logged-in users have access to see other components than home component and also all routes before logging-in be redirected to home component).


Solution

  • The Angular documentation recommends defining a wildcard route.

    Add a wildcard route to intercept invalid URLs and handle them gracefully. A wildcard route has a path consisting of two asterisks. It matches every URL. The router will select this route if it can't match a route earlier in the configuration. A wildcard route can navigate to a custom "404 Not Found" component or redirect to an existing

    The router selects the route with a first match wins strategy. Wildcard routes are the least specific routes in the route configuration. Be sure it is the last route in the configuration.

    In your case:

    { path: '**', redirectTo: 'home'}