Search code examples
angularangular-router-guardsangular-injector

Angular inject Router into CanActivateFn to use in runInInjectionContext


I have a guard that needs to get something async and then decide with that value if a user needs to be redirected with the URLTree.

The code itself is very simple:

export const otapGuard: CanActivateFn = async (route, state) => {
  let APPID = chrome.runtime.id;

  const { omgeving } = await chrome.storage.local.get('omgeving');

  if (omgeving === getAppEnvironment(APPID)) {
    return true;
  }

  inject(Router).createUrlTree([])
};
  {
    path: 'popup',
    loadChildren: () => import('./popup/popup.module').then(m => m.PopupModule),
    resolve: {
      user: TokenResolver
    },
    canActivate: [OtapGuard, MyMsalGuard]
  },

However this is not possible due to inject being unavailable after an await. It's basically the same problem as this: Angular ResolveFn - inject() must be called from an injection context. But no "code" solution has been provided.

I need to use runInInjectionContext with the Router added as an Injection, but I don't understand how to do this


Solution

  • You can inject the router ahead of the await :

    export const otapGuard: CanActivateFn = async (route, state) => {
      let APPID = chrome.runtime.id;
      const router = inject(Router);
      const { omgeving } = await chrome.storage.local.get('omgeving');
    
      if (omgeving === getAppEnvironment(APPID)) {
        return true;
      }
    
      return router.createUrlTree([])
    };