简体   繁体   中英

How to provide app feature routes within web shell module

I'm getting the following error

Uncaught Error: NG0203: inject() must be called from an injection context such as a constructor, a factory function, a field initializer, or a function used with `EnvironmentInjector#runInContext`.

I'm trying to create a Nx library module to share a web shell auth logic to share with multiple apps. I'd like each app to be able to something along the lines of:

  providers: [
    {
      provide: HOME_PAGE,
      useValue: 'my-app-homepage',
    },
    {
      provide: LOAD_FEATURE_ROUTES,
      useValue: async () => (await import('./feature-routes')).FEATURE_ROUTES
    },
  ],

But how do I get these into my library module's routing to use in the middle like so

function createRoutes(): Routes {
  const homePage = inject(HOME_PAGE)
  const childRoutes = inject(LOAD_FEATURE_ROUTES)

  return [
    {
      path: 'auth',
      loadChildren: async () => (await import('./auth-routes')).AUTH_ROUTES,
    },
    {
      path: homePage, // <---- I want to inject app feature routes
      loadChildren: childRoutes
    },
    { path: '', redirectTo: 'auth', pathMatch: 'full' },
    { path: '**', redirectTo: 'auth' },
  ];
}

Obviously the cause of the error for the following is but now sure what to replace this with:

    RouterModule.forRoot(inject(APP_ROUTES), {
      scrollPositionRestoration: 'top',
    })],

Full code:

import { inject, InjectionToken, NgModule } from '@angular/core';
import { Routes, RouterModule, LoadChildrenCallback } from '@angular/router';
import { HOME_PAGE } from '@my-org/shared/auth-login/data-access/store';

export const APP_ROUTES = new InjectionToken<Routes>('APP_ROUTES');
export const LOAD_FEATURE_ROUTES = new InjectionToken<LoadChildrenCallback>('LOAD_FEATURE_ROUTES');

function createRoutes(): Routes {
  const homePage = inject(HOME_PAGE)
  const childRoutes = inject(LOAD_FEATURE_ROUTES)

  return [
    {
      path: 'auth',
      loadChildren: async () => (await import('./auth-routes')).AUTH_ROUTES,
    },
    {
      path: homePage,
      loadChildren: childRoutes
    },
    { path: '', redirectTo: 'auth', pathMatch: 'full' },
    { path: '**', redirectTo: 'auth' },
  ];
}

@NgModule({
  imports: [
    RouterModule.forRoot(inject(APP_ROUTES), {
      scrollPositionRestoration: 'top',
    })],
  providers: [
    {
      provide: APP_ROUTES,
      useFactory: createRoutes,
      deps: [
        APP_ROUTES,
        LOAD_FEATURE_ROUTES
      ]
    }
  ],
  exports: [RouterModule],
})
export class SharedAuthLoginRoutingModule {
}

Note I'm using Angular 15 and lazy loading APP_ROUTES with standalone components.

Managed to do this with ROUTES dependency injection

{
   provide: ROUTES,
   multi: true,
   useFactory: createRoutes
}
const createRoutes = () => {
  const homePage = inject(HOME_PAGE);
  const featureChildrenRoutes = inject(LOAD_FEATURE_ROUTES);

  console.log(homePage) // works

  const routes: Routes = [
    {
      path: 'auth',
      loadChildren: async () => (await import('@my-org/shared/auth-login/feature')).SharedAuthLoginFeatureModule;
      },
    },
    /**
     * App specific routes injected via `HOME_PAGE` and `LOAD_FEATURE_ROUTES`
     */
    {
      path: homePage,
      loadChildren: featureChildrenRoutes,
      canActivate: [AuthGuard],
      data: { authGuardPipe: authPipeGenerator }
    },
    { path: '', redirectTo: 'auth', pathMatch: 'full' },
    { path: '**', redirectTo: 'auth' },
  ];

  return routes;
}
// tree shakeable injection token
export const HOME_PAGE = new InjectionToken<string>('HOME_PAGE', {
  providedIn: 'root',
  factory: () => { throw new Error(`Provider required e.g. { provide: HOME_PAGE, useValue: 'home' }`) }
});

// tree shakeable injection token
export const LOAD_FEATURE_ROUTES = new InjectionToken<LoadChildrenCallback | undefined>('LOAD_FEATURE_ROUTES', {
  providedIn: 'root',
  factory: () => {throw new Error(`Provide lazy loaded App specific routes e.g. \`async () => (await import('./app.routes')).appShellRoutes}\``)}
})

Now I can have an AppModule import AppShellModule which imports WebShellModule

AppModule - just imports app shell
AppShellModule - imports web shell, defines the app feature routes
WebShellModule - landing page shell with navbar, auth (login, register pages etc.)

My WebShellModule is reuseable across multiple apps

@NgModule({
  imports: [
    BrowserAnimationsModule,
    HttpClientModule,
    RootNgrxModule, // provide store, effects, router store
    RouterModule.forRoot([], {
      scrollPositionRestoration: 'top',
    }),
    FirebaseV7Module, // provide app, auth, firestore
    HomePageComponent, // Standalone component, navbar
  ],
  providers: [
    {
      provide: ROUTES,
      multi: true,
      useFactory: createRoutes
    },
  ]
})
export class WebShellModule { }

AppShellModule is responsible for providing the DI tokens eg

    {
      provide: HOME_PAGE,
      useValue: 'procurement',
    },
    {
      provide: LOAD_FEATURE_ROUTES,
      useValue: async () => {
        return (await import('./procurement.routes')).procurementShellRoutes;
      },
    },

I haven't figured everything out but this seems the direction to take.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM