Lazy loading angular modules but not using the route prefix - javascript

I have an app where I'm lazy loading a module called lazy. That module is lazy loaded via this:
{
path:'lazy',
loadChildren:
'./lazy/lazy.module#LazyModule'
}
The lazy module has the following routes in it:
const routes = [
{
path: '',
component: LazyComponent
},
{
path: 'faq',
component: FaqComponent
},
{
path: 'details',
component: DetailsComponent
},
]
The above works fine but I can only access the routes of my lazy loaded module via /lazy/faq or /lazy/details. But what I really want is to not use the route prefix lazy and access the routes of my lazy loaded module directly via /faq and /details.
Is this possible to do? I have not been able find a solution for this.

The url of components within lazy loaded modules is a combination of the url to the module e.b 'lazy'-> LazyLoadedModule plus the relative path within that module e.g 'faq->FaqComponent.
So the url is path/to/lazy-module + 'relative/path'. In your case lazy/faq. You cannot omit the prefix.
What you can do is to add a redirect in your routing config:
path: 'faq',
pathMatch: 'full,
redirectTo: 'lazy/faq'
When you use routing within your lazy module you can use relative routes: this.router.navigate(['faq']) but the url in the browser would be lazy/faq though.
Another option would be to use empty route for loading your module:
path:'',
loadChildren: ...
But that would load your module immediately when your application starts.

Related

Angular Lazy Loading Modules and entryComponents error

I'm lazy loading an angular module and while trying to open my DatesModal I'm getting this error:
No component factory found for DatesModal. Did you add it to #NgModule.entryComponents?
My lazyModule looks like this:
declarations: [DatesModal]
entryComponents: [DatesModal]
Im definitely adding the DatesModal in the entryComponents array of the lazyModule. Anyone got any idea what I could be missing here?
Please let me know if you need more info to answer this question.
It looks like you want to get/import this module in other modules, however this module is not visible to others. Try to export your module:
exports: [DatesModal]
UPDATE:
As Angular docs says:
For production apps you want to load the smallest code possible. The
code should contain only the classes that you actually need and
exclude components that are never used. For this reason, the Angular
compiler only generates code for components which are reachable from
the entryComponents; This means that adding more references to
#NgModule.declarations does not imply that they will necessarily be
included in the final bundle.
If a component isn't an entry component and isn't found in a template,
the tree shaker will throw it away. So, it's best to add only the
components that are truly entry components to help keep your app as
trim as possible.
To make your module to be lzay loaded, you need to do in routes:
const routes: Routes = [
{
path: 'customers',
loadChildren: () => import('./customers/customers.module').then(mod => mod.CustomersModule)
},
{
path: 'orders',
loadChildren: () => import('./orders/orders.module').then(mod => mod.OrdersModule)
},
{
path: '',
redirectTo: '',
pathMatch: 'full'
}
];
Read this docs about how to make your modules to be lazy loaded.
Have you used any third-party library (or yourself) to dynamic create this component in lazy-load module?
If so, you need to add this component in the AppModule's (or up-level non-lazy-load module) entrycomponents.
More detail you can see this issue

Angular Routes: Problem defining a NotFoundComponent with multiple routings files

I am creating a NotFoundComponent so that every non-existing url, a friendly page will apear to the user.
My Angular 6 project has 5 features(CRUDL):
CompanyComponent,
EmployeeComponent,
BranchComponent,
BenefitsComponent,
MainComponent
Each component have it own .module and .routing, for example the company.routing.ts defines the route like this:
export const routes: Routes = [
{
path: "branch",
component: EmptyComponent,
}
...
#NgModule({
imports: [
RouterModule.forChild(routes),
...
it also defines its childrens, like path: "branch/:id".
So, i have no problem with the way i built the routing.
The problem I am facing now is the way I can define a path to the NotFoundComponent.
Because I don't have a single file where I define my routes, if I put the definition of the /404 page on the on the bottom of routers definition in the main.routing.ts, every other route defined on the features(like the company.routing.ts) will be redirected to the /404, since angular uses the first match strategy.
Things i tried so far:
on the main.routing.ts:
export const routes: Routes = [
{
path: "main",
component: MainComponent,
},
{
path: "404",
resolve: {
routeTitle: TitleResolver,
},
component: NotFoundComponent,
},
{
path: "",
pathMatch: "full",
redirectTo: "/main",
},
{
path: "**",
redirectTo: "/404",
}
if I put this way, when I try accessing the route /company (defined in the company.routing.ts) it will be redirected to the /404.
I also tried defining it on any a routing of one of my features, like on the company.routing.ts
{
path: "**",
redirectTo: "/404",
}
Than, a funny thing happened, if I define this piece of code on the benefits.routing.ts, i can access /benefits but /branch, /employee and the rest of the routes will be redirected to /404.
if I define it on branch, I can access /benefits, /branch but /employee and the rest of the routes will be redirected to /404.
I could just place this code on the last feature loaded and it would work but I would like to know if I can solve this with another approach, can't I define a route that I want to be the last one loaded?
thanks in advance.

Angular 6: How to use multiple loadChildren with same route?

I have something like:
const routes: Routes = [
{
path: ':path', component: SiteRoot, children: [
{ path: '', loadChildren: '../modules/maple/template.module#TemplateModule' }
]
}
];
I wish to use this :path url to match multiple module dynamically. each module have there own internal Route.
Is there any way I can achieve this?
I tried ViewContainerRef with ResolveComponentFactory but it does not work with module only component. Event with NgModuleFactoryLoader, Routes cannot be applied.
EDIT, to make everything clear:
What I am trying to achieve is to have different module display on same route path. For example user can see user dashboard at "home" path, and admin can see admin dashboard at "home" path as well.
This feature is defined by business logic, so, I cannot change admin dashboard to another url
I think you are trying to create your routing module incorrectly. Anyway, you should write why you need this. I'll try to answer. Every module should have it's own path, so routing module should be strict and static. If you trying it for security, use guards and hide item from menu component.
If you need URLs like this: "/username1/profile", "/username2/profile" you can simply use code like yours, or use lazy loading. create routing file for parent module:
{ path: ':username', loadChildren: '../users/user.module#UserModule' }
Than create routing file for child module:
{ path: '', loadChildren: 'UserComponent', children: [
{ path: '', redirectTo: 'profile' },
{ path: 'profile', component: ProfileComponent}
]
}
Updated By your case:
by your case you can change your HTML file. For example in app.component.html if your code is:
<div>
<router-outlet></router-outlet>
</div>
You can change it with:
<div *ngIf="isLoggedIn | async">
<admin-panel></admin-panel>
</div>
<div *ngIf="(!isLoggedIn | async)">
<router-outlet></router-outlet>
</div>

Angular feature routing module - Child component not loaded

I have a feature module that I load in the AppModule, the AppRoutingModule looks like
const appRoutes: Routes = [
...
{
path: 'move-request/:id',
loadChildren: 'app/modules/move_requests/move_requests.module#MoveRequestModule'
},
...
];
And the configuration of routing for the feature module looks like
const moveRequestRoutes: Routes = [
{
path: '',
component: MoveRequestFormComponent,
data: {title: 'Move Request'}
},
{
path: 'move-request-success',
component: RequestSuccessComponent,
data: {title: 'Move request success'}
},
];
I would like to navigate to MoveRequestFormComponent as the default component when move-request/:id is routed to, this works fine, but when I call
this.router.navigate(['/move-request-success', {}]);
In MoveRequestFormComponent after some response from the server, I get
zone.js:665 Unhandled Promise rejection: Cannot match any routes. URL Segment: 'move-request-success' ; Zone: <root> ;
This configuration was working before I switched to Angular 6, Is it because of the change in the AppModule, where I have excluded this feature module as an import?
Any assistance on what I am missing would be much appreciated. As I have also tried with having a third component which will be the default component and uses the router-outlet to render the children and have a children property on this route to have as children
{
path: '',
component: MoveRequestFormComponent,
data: {title: 'Move Request'}
},
{
path: 'move-request-success',
component: RequestSuccessComponent,
data: {title: 'Move request success'}
},
But that also did not work, it stayed on the MoveRequestFormComponent, when 'move-request-success' was navigated to.Or maybe I should change the approach?
You don't have to import the feature module in AppModule as it is lazily-loaded. When you navigate to move-request/:id/move-request-success, the path matches the default route with path:'', and then it will look for and children of that route. You should add pathMatch:'full' to the first route, which is the default in this case. Since the mentioned route matches the first route and is unable to find and match any children, it is showing the error.
this.router.navigate(['/move-request-success', {}]);. If you add a / to a route this means you use absolute path from root. Have you tried without / ?
EDIT:
I think I see your problem. You navigate to a module with multiple components, which means after lazy loading the router configuration from the loaded module is used. This means
move-request/:id
Is the root of your module and every subroute needs to include the modules root in the url:
Your route should be move-request/:id/move-request-success
Urls in lazy loaded modules are:
module root (in your case move-request/:id) + configured route of the specific component (in your case move-request-success)

Angular 4 lazy load module doesn't work with named child outlet

I am trying to implement lazy loading for a module. This module has a bunch of child routes with a unique outlet name. This doesn't seem to work when I try to visit the routes.
This can be seems from this example that I saved: https://plnkr.co/edit/NNXAoZItM00RIIxzemts?p=preview
You can see that I have the child route set to
{ path: 'list', component: HeroListComponent, outlet: 'abc' },
in hero-routing.module.ts
and router outlet to:
<router-outlet name="abc"></router-outlet>
in hero.component.ts
I should be able to visit localhost:3000/heroes/(abc:list) when I am running it locally, but it doesn't seem to work.
Note: You can run the plunker example locally by download the zip file and running npm install then npm start.
The child routes do not seem to work with default unamed routes.
Change the lazy loaded module routes to include a redirect from default unamed route to a named route.
const routes: Routes = [
{ path: '', redirectTo: 'start', pathMatch: 'full' },
{ path: 'start', component: HeroComponent,
children: [
{ path: 'list', component: HeroListComponent, outlet: 'abc' },
{ path: ':id', component: HeroDetailComponent }
]
}
];
Finally change the navigation link for 'heroes' lazy loaded module to include the named outlet information. Be sure to specify the complete url as '/heroes/start', do not leave it to the default '/heroes'.
<a [routerLink]="['/heroes/start',{outlets: {abc:['list']}}]"
routerLinkActive="active">Heroes</a>

Categories

Resources