Search code examples
angularangular-routingangular-router

When reloading an Angular app go always to the root page ignoring routing


I have a simple Angular app which uses the router.

My routing logic is simple

Routes = [
  { path: '', component: MyMainComponent },
  { path: 'error', component: ErrorComponent },
]

If an error occurs in the app, the logic navigates to the ErrorComponent and therefore what I see on the browser url is http://localhost:4200/error.

If the user reloads the app from here (e.g. with CMD+R) the app goes back to the Error page. Is there a way to force a reload to go to the Main even if we reload a url pointing to an existing route path?


Solution

  • It is the question of design. You should give angular information if error really happened.

    • It might be a service which stores last error and when navigation is performed this service is checked. So when page is refreshed, the service would not contain anything and you can navigate to default route
    • or you can provide additional queryparameter to the error route which would be removed when navigation ends and when user refresh the page it would not be in the url. So the only way to see this param – navigate inside of the app.

    In fact these approaches are alike – different just in the way you store information of internal navigation.

    Not depenging on what approach you choose, for restricting navigation to specific route you can use CanActivate guard https://angular.io/api/router/CanActivate