2

I have an Angular app running inside an iframe that has a route guard for the module that I'm running. The route guard is activated whenever I navigate to the page using links inside the app or through the address bar, and routes the app to the correct component. But for some reason, when I click the back button from within the components, the module's route guard fails to fire and the app is navigated to the base component of the module - which should not be happening.

I've tested and confirmed that router events do get fired when I press the back button inside one of the components using this :

export class FourthComponent {

  constructor(private readonly router: Router) {
    this.router.events.subscribe((event: NavigationStart) => {
      if (event.navigationTrigger === 'popstate') {
        console.log('back or forward button clicked');
      }
    });
  }

The console log does print whenever I click the back button from the secondary component screen.

Here is the child module's routing module routes array:

const routes: Routes = [
  {
    path: '',
    canActivate: [SubModuleGuard],
    children: [
      {
        path: 'first',
        component: FirstComponent
      },
      {
        path: 'second',
        component: SecondComponent
      },
      {
        path: 'third',
        component: ThirdComponent
      },
      {
        path: 'fourth',
        component: FourthComponent
      },
      {
        path: '**',
        component: BaseComponent
      }
    ]
  }
];

For some reason, every time I click the back button from the FourthComponent I'm navigated to the BaseComponent (Possibly the case for all child components of SubModule). If I then click the back button again, it does a back operation for the parent of the iframe too.

Please tell me why the route guard (in this case SubModuleGuard) won't fire, and how do I force the route guard to fire when the back button is clicked?

Harrys Kavan
  • 741
  • 9
  • 28
Flame of udun
  • 2,136
  • 7
  • 35
  • 79

1 Answers1

0

As suggested by Andrei above, use runGuardsAndResolvers: 'always' when declaring your route. See below:

const routes: Routes = [
  {
    path: '',
    canActivate: [SubModuleGuard],
    runGuardsAndResolvers: 'always',
    children: [
      {
        path: 'first',
        component: FirstComponent
      },
      {
        path: 'second',
        component: SecondComponent
      },
      {
        path: 'third',
        component: ThirdComponent
      },
      {
        path: 'fourth',
        component: FourthComponent
      },
      {
        path: '**',
        component: BaseComponent
      }
    ]
  }
];

Reference docs: https://angular.io/api/router/RunGuardsAndResolvers