I want to lazy load a module after API response
below are my routes
const routes: Routes = [
{ path: "", component: LandingComponent },
{ path: 'student', loadChildren: () => import('./student.module').then(m => m.StudentModule) },
{ path: 'school', loadChildren: () => import('./school.module').then(m => m.SchoolModule) },
{ path: "**", component: PagenotfoundComponent }
];
What I want is something like Facebook doing for profile handling for example
facebook.com/ABCD is my profile (A Different Module)
facebook.com/EFGH is my page (Another Different Module)
In angular, I want something like when I access a URL like site.com/abcd it will first check if route param abcd is a user profile or an institution page and then based on the response it will lazy load the student or school module
I have a couple of ideas for this like make a common component and then in that component make API calls and check if route param is student profile or school profile then load their components accordingly something like below
const routes: Routes = [
{ path: "", component: LandingComponent },
{ path: ':profile_token', component : CommonComponent },
{ path: "**", component: PagenotfoundComponent }
];
then in CommonComponent
<ng-container *ngIf="isProfileRoute">
<app-user-profile></app-user-profile>
</ng-container>
<ng-container *ngIf="isSchoolRoute">
<app-school-profile></app-school-profile>
</ng-container>
But here in the method as you can see both components are loading and I feel its not a good way to handle it
so if is there any way to lazy load a whole module containing routes and components based on API call it will be really great and helpful.
2
Answers
The problem is that you are calling app-user-profile and app-school-profile in your common component. If you want Angular to lazy load your module as soon as the route is called you have to use the Angular Router (https://angular.io/guide/router).
You have to specify a where the router should create the content.
In your common component you have to create a router redirect to either the profile or the school route:
Maybe dynamic loading in the routing could help you?
app-routing.module.ts:
And in the AppRoutingModule:
And before the routes array: