Search code examples
angularangular-routing

I want to always redirect to home page


I am testing an app, and at each changes I do in js, I would like that it load the home page.

Right now, if I am on a specific route, it will hot reload that route.

Is there a way to force homepage on refresh in angular ?


Solution

  • One approach may be to add a route guard that checks for some global variable.

    For example; first create a service:

    import { Injectable } from '@angular/core';
    @Injectable({
      providedIn: 'root',
    })
    export class MyRedirectCheckService {
      redirectToHomePage = true;
    }
    

    Create a route guard that uses the service, something like this:

    import { Injectable } from '@angular/core';
    import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
    @Injectable({
      providedIn: 'root',
    })
    export class checkFirstLoadGuard implements CanActivate {
      canActivate(
        next: ActivatedRouteSnapshot,
        state: RouterStateSnapshot, 
        myRedirectCheckService: MyRedirectCheckService ): boolean {
        return myRedirectCheckService.redirectToHomePage;
      }
    }
    

    Then add the canActivate route guard to your router:

    const routes: Routes = [
              { path: 'main', component: MainComponent },
              { path: 'child', component: ChildComponent, canActivate: [CheckFirstLoadGuard]},
              { path: '**', component: AdminDashboardComponent }
            ]
    ];
    

    In your main component constructor, be sure to toggle the value:

    constructor(myRedirectCheckService: MyRedirectCheckService) {
      myRedirectCheckService.redirectToHomePage = false;
    }
    

    This is just one approach, and code is not tested in the context of an actual app.