0

I am using Angular CLI to build app. I have configured routes as shown below:

const routes: Routes = [
 {path: 'Home', component: HomeComponent},
  {path: 'About', component: AboutUsComponent},
  { path: '**', pathMatch: 'full', redirectTo: 'Home' }
];

I have a requirement that on refresh of the page I need to redirect to Home path.
Note: I have tried doing it with guards but failed to achieve desired result. Please help me out with the steps.

Thanks in advance

Tavish Aggarwal
  • 1,020
  • 3
  • 22
  • 51
  • what is that your trying to do? on which condition it should navigate to home copmonent? – Aravind Jun 18 '17 at 05:04
  • 2
    Explain whoever gave you this requirement that it's a bad requirement. Users expect the currrent page to refresh when hitting the refresh button, because that's what it's for. It shouldn't navigate elsewhere. – JB Nizet Jun 18 '17 at 06:11
  • If it is browser refresh it should be done on a server / load balancer side – smnbbrv Jun 18 '17 at 06:12
  • What have you done with the guard? – Meir Jun 18 '17 at 06:37
  • It is done through guard only.You need to check on what condition it should redirect to home page and write that logic in guard. – pritesh Jun 18 '17 at 06:48
  • Thanks for the suggestions. It requirement I have. @Aravind When ever user refresh it should got to home page. JB Nizet yup I know but As per the requirement we have written separate js file and when user refresh particular page it breaks as home page js is not loaded. – Tavish Aggarwal Jun 24 '17 at 11:21
  • @pritesh Yup I tried with guards but I am not getting exact way to know when refresh happens in guard – Tavish Aggarwal Jun 24 '17 at 11:24

2 Answers2

0

you can add a redirect in your app.component to your home page. app.component load once and will be load again in a new refresh.

Yalin
  • 345
  • 2
  • 9
0

This is applicable to Ang7 In app.component.ts,

<strong>import { Location } from '@angular/common'

then in ngOnInit() within the same file add:

if(location.pathname != "/"){location.replace("/")}

Assuming you have Route setup and your home URL path is "/"

Llazar
  • 3,167
  • 3
  • 17
  • 24