Crocsx
Crocsx

Reputation: 7589

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 ?

Upvotes: 0

Views: 42

Answers (2)

terahertz
terahertz

Reputation: 3491

use

window.location = '' 

instead of

this.router.navigate([''])

to force refresh

if using inside element, use href attribute instead of routerLink attribute

Upvotes: 1

JeffryHouser
JeffryHouser

Reputation: 39408

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.

Upvotes: 2

Related Questions