juniorDeveloper
juniorDeveloper

Reputation: 225

Angular 5 page refresh always lands in the home page instead of being on the same page

I have the following routes in the application. the problem here is if I navigate to say getEmp-by-id or page-not-found and hit refresh, then application is landing on app-home,. But I want it to stay on the same page where refresh is hit.I am not implementing any RouteGuards, simple navigations. Is there a way I can acheive this.

const appRoutes: Routes = [
  {path: '', component: HomeComponent,  children: [
    {path: 'app-home', component: AppHomeComponent, resolve: {ApphomeResolver : AppHomeResolver}},
    {path: 'getEmp-by-id', component: EmpComponent},
    {path: 'page-not-found', component: pageNotFoundComponent},] 
  }, 
  {path: '**', redirectTo: 'page-not-found', pathMatch: 'full'}
];




export class EmpComponent implements OnInit {

  constructor(private router: Router, private route: ActivatedRoute, private alertService: AlertService, private employeeService: EmployeeService) { }
  ngOnInit() {}

  onSubmit() {

         this.employeeService.getEmployee(empId).subscribe(
        (data) => {

          var responseCode = JSON.parse(data).responseCode;
          var responseMessage = JSON.parse(data).responseMessage
          if (responseCode === 200) {
                this.router.navigate(['../emp-details'], { relativeTo: this.route });
          } else {
          this.router.navigate(['../page-not-found'], { relativeTo: this.route });
          }
        }, error => {
          this.router.navigate(['../page-not-found'], { relativeTo: this.route });
        });
    } else {
      this.alertService.error("Error");
    }
  }
}

Upvotes: 3

Views: 2380

Answers (1)

Praveen Kumar
Praveen Kumar

Reputation: 543

One way of handling page refreshes is to using hash routing. To implement this, write the following code in app.module.ts:

import { APP_BASE_HREF, LocationStrategy, HashLocationStrategy } from '@angular/common';

@NgModule({
......
providers: [
    { provide: APP_BASE_HREF, useValue: '', }
    , { provide: LocationStrategy, useClass: HashLocationStrategy }
    .....
]})
export class AppModule {

}

Please note that this will add # to your route.

Upvotes: 2

Related Questions