简体   繁体   中英

Angular 8: share component state across lazy loaded modules

I have main app module and few lazy loaded modules. There is one side menu with which controls the whole app navigation, everything works fine but every time I switch from one module to the next lazy loaded module the whole menu reloads and the menu active item state gets reset, the user has to click on the side menu a second time to switch between the links. When a module has been loaded, after the second click on the side menu it works ( the side menu remains open, shows where the user clicked->state preserved) but as soon as he clicks on a link routing to another module the side menu closes.

any kind help is much appreciated thanks.

this is when routing to another page of same module, the state remains

菜单打开

*as soon as we click on a route to component of another module, the menu resets and user can't know which module did he clic * 菜单关闭

MAIN APP ROUTES FILE

export const routes: Routes = [

    {

    path: '', component: AppMainComponent,
    canActivate: [AuthGuard],
    children: [

        { path: '', redirectTo: '/dashboard', pathMatch: 'full' },

        { path: 'dashboard', component: DashboardComponent },

           ]
},

{ path: 'regional-hierarchy', loadChildren: './regionalhierarchy/regionalhierarchy.module#RegionalhierarchyModule' },
{ path: 'product', loadChildren: './product/product.module#ProductModule' },
{ path: 'pricing', loadChildren: './pricing/pricing.module#PricingModule' },
{ path: 'distributory', loadChildren: './distribution/distribution.module#DistributionModule' },
{ path: 'stock', loadChildren: './stock/stock.module#StockModule' },
{ path: 'factory', loadChildren: './factory/factory.module#FactoryModule' },
{ path: 'sole', loadChildren: './sole/sole.module#SoleModule' },
{ path: 'shopcredit', loadChildren: './shopcredit/shopcredit.module#ShopcreditModule' },
// { path: 'shop', loadChildren: './shops/shops.module#ShopsModule' },
{ path: 'stock', loadChildren: './stock/stock.module#StockModule' },

{ path: 'error', component: AppErrorComponent },
{ path: 'accessdenied', component: AppAccessdeniedComponent },
{ path: '404', component: AppNotfoundComponent },
{ path: '**', redirectTo: '/404' },

];

export const AppRoutes: ModuleWithProviders = 
RouterModule.forRoot(routes, { scrollPositionRestoration: 'enabled' });

LAZY LOADED MODULE'S ROUTING FILE

const routes = [
{
 path: '',
 component: RegionalhomeComponent,
 canActivate: [AdminGuard],
 children: [
  { path: 'createRegion', component: CreateRegionComponent },
  { path: 'viewRegions', component: ViewRegionsComponent },
  { path: 'createZone', component: CreateZoneComponent },
  { path: 'viewZones', component: ViewZonesComponent },
  { path: 'createArea', component: CreateAreaComponent },
  { path: 'viewAreas', component: ViewAreasComponent },
  { path: 'createTerritory', component: CreateTerritoryComponent },
  { path: 'viewTerritories', component: ViewTerritoriesComponent },
  { path: 'createCity', component: CreateCityComponent },
  { path: 'viewCities', component: ViewCitiesComponent },
  { path: 'createTown', component: CreateTownComponent },
  { path: 'viewTowns', component: ViewTownsComponent },
  { path: 'createRoute', component: CreateRouteComponent },
  { path: 'viewRoutes', component: ViewRoutesComponent },
  { path: '', component: RegionalhomeComponent }
  ]
 }
]

@NgModule({
 declarations: [],
 imports: [
  CommonModule,
  RouterModule.forChild(routes)
 ]
})
export class RegionalhierarchyRoutingModule { }

**MAIN APP COMPONENT HTML **

<div class="layout-wrapper" [ngClass]="{'layout-horizontal': menuMode === 'horizontal',
'layout-overlay': menuMode === 'overlay',
'layout-static': menuMode === 'static',
'layout-slim': menuMode === 'slim',
'layout-menu-light': lightMenu === true,
'layout-menu-dark': lightMenu === false,
'layout-overlay-active': overlayMenuActive,
'layout-mobile-active': staticMenuMobileActive,
'layout-static-inactive': staticMenuDesktopInactive,
'layout-rtl': isRTL}" [class]="topbarColor" (click)="onLayoutClick()">
<app-topbar></app-topbar>

<app-menu [reset]="resetMenu"></app-menu>
<app-right-menu></app-right-menu>

<div class="layout-main">
    <div class="layout-content">
        <router-outlet></router-outlet>
    </div>
</div>

<div class="layout-content-mask"></div>

is component whose state i need preserved when switching to a lazy loaded module, the file itself is very large so am pasting only a part of it here..

app-menu component

       { label: 'Home', icon: 'pi pi-fw pi-home', routerLink: ['/'] },
        {
            label: 'Sale', icon: 'pi pi-fw pi-copy',
            items: [
                {
                    label: 'Territorial Structure', icon: 'pi pi-fw pi-clone',
                    skipLocationChange: true,
                    items: [
                        {
                            label: 'Region', icon: 'pi pi-fw pi-sign-in',
                            items: [
                                {
                                    label: 'Add Region', icon: 'pi pi-fw pi-plus', routerLink: ['/regional-hierarchy/createRegion'],
                                },
                                {
                                    label: 'View Regions', icon: 'pi pi-fw pi-window-maximize', routerLink: ['/regional-hierarchy/viewRegions'],
                                    queryParams: { 'recent': 'true' },
                                    routerLinkActiveOptions: "{exact: true}",
                                    command: (event) => {
                                        //event.originalEvent: Browser event

                                        //event.item: menuitem metadata
                                    },
                                    target: '_blank'
                                }
                            ]
                        },
                        {
                            label: 'Zone', icon: 'pi pi-fw pi-sign-in',
                            items: [
                                { label: 'Add Zone', icon: 'pi pi-fw pi-plus', routerLink: ['/regional-hierarchy/createZone'], target: '_blank' },
                                { label: 'View Zones', icon: 'pi pi-fw pi-window-maximize', routerLink: ['/regional-hierarchy/viewZones'], target: '_blank' }
                            ]
                        },
                        {
                            label: 'Area', icon: 'pi pi-fw pi-sign-in',
                            items: [
                                { label: 'Add Area', icon: 'pi pi-fw pi-plus', routerLink: ['/regional-hierarchy/createArea'], target: '_blank' },
                                { label: 'View Areas', icon: 'pi pi-fw pi-window-maximize', routerLink: ['/regional-hierarchy/viewAreas'], target: '_blank' }
                            ]
                        },
                        {
                            label: 'Territory', icon: 'pi pi-fw pi-sign-in',
                            items: [
                                { label: 'Add Territory', icon: 'pi pi-fw pi-plus', routerLink: ['/regional-hierarchy/createTerritory'], target: '_blank' },
                                { label: 'View Territories', icon: 'pi pi-fw pi-window-maximize', routerLink: ['/regional-hierarchy/viewTerritories'], target: '_blank' }
                            ]
                        },

and above this is the app.main.component

<router-outlet></router-outlet>

I had to move the lazy loaded modules' routing inside the main route's children array, this fixed the issue. Thanks everyone

 {

    path: '', component: AppMainComponent,
    canActivate: [AuthGuard],
    children: [

        { path: '', redirectTo: '/dashboard', pathMatch: 'full' },

        { path: 'dashboard', component: DashboardComponent },

        { path: 'create-dist-trade-offer', canActivate: [AdminGuard], component: CreateDistTradeOfferComponent },
        { path: 'create-dist-trade-offer', canActivate: [AdminGuard], component: CreateDistTradeOfferComponent },
        { path: 'distribution-trade-offers', component: TraderOfferComponent },
        { path: 'multiple-distribution-trade-offers', canActivate: [AdminGuard], component: DistTradeOfferComponent },
        { path: 'multiple-sole-trade-offers', canActivate: [AdminGuard], component: SoleMultipleTradeOfferComponent },
        { path: 'sole-trade-offers', component: SoleTradeOfferComponent },
        { path: 'create-sole-trade-offer', canActivate: [AdminGuard], component: CreateSoleTradeOfferComponent },
        { path: 'edit-sole-trade-offer', canActivate: [AdminGuard], component: EditSoleTradeOfferComponent },
        { path: 'create-primary-order', component: CreatePrimaryOrderComponent },
        { path: 'create-secondary-order', component: CreateSecondaryOrderComponent },
        { path: 'view-secondary-orders', component: ViewSecondaryOrdersComponent },
        { path: 'view-primary-orders', component: ViewPrimaryOrdersComponent },
        { path: 'create-order-booker', canActivate: [AdminGuard], component: CreateOrderBookerComponent },
        { path: 'add-pjp', component: AddPjpComponent },
        { path: 'add-pjp-rule', component: CreatePjpRuleComponent },
        { path: 'view-pjp', component: ViewPjpComponent },

        { path: 'view-order-bookers', component: ViewOrderBookerComponent },
        { path: 'create-delivery-man', component: CreateDeliverymanComponent },
        { path: 'view-delivery-mans', component: ViewDeliverymansComponent },
        { path: 'create-order-booker-route', canActivate: [AdminGuard], component: CreateObRouteComponent },
        { path: 'view-order-booker-routes', component: ViewObRoutesComponent },
        { path: 'edit-order-booker-routes', canActivate: [AdminGuard], component: EditObRouteComponent },
        { path: 'create-delivery-man-route', component: CreateDmRouteComponent },
        { path: 'edit-delivery-man-route', component: UpdateDmRouteComponent },
        { path: 'view-delivery-man-routes', component: ViewDmRoutesComponent },
        { path: 'invoice-secondary-order', component: InvoiceSecondaryOrderComponent },
        { path: 'invoice-primary-order', component: InvoicePrimaryOrderComponent },
        { path: 'multiple-invoice-secondary-order', component: MultipleInvoiceSecondaryOrderComponent },
        { path: 'dispatch-primary-order', component: DispatchPrimaryOrderComponent },
        { path: 'special-dispatch-primary-order', component: SpecialDispatchPrimaryOrder },
        { path: 'dispatch-secondary-order', component: DispatchSecondaryOrderComponent },
        { path: 'deliver-secondary-order', component: DeliverSecondaryOrderComponent },
        { path: 'load-form', component: LoadFormComponent },
        { path: 'delivery-report', component: DeliveryReportComponent },

        { path: 'dist-sale-report', component: DistributionSaleReportComponent },

        { path: 'regional-hierarchy', loadChildren: './regionalhierarchy/regionalhierarchy.module#RegionalhierarchyModule' },
        { path: 'product', loadChildren: './product/product.module#ProductModule' },
        { path: 'pricing', loadChildren: './pricing/pricing.module#PricingModule' },
        { path: 'distributory', loadChildren: './distribution/distribution.module#DistributionModule' },
        { path: 'stock', loadChildren: './stock/stock.module#StockModule' },
        { path: 'factory', loadChildren: './factory/factory.module#FactoryModule' },
        { path: 'sole', loadChildren: './sole/sole.module#SoleModule' },
        { path: 'shopcredit', loadChildren: './shopcredit/shopcredit.module#ShopcreditModule' },
        // { path: 'shop', loadChildren: './shops/shops.module#ShopsModule' },
        { path: 'stock', loadChildren: './stock/stock.module#StockModule' },

        { path: 'error', component: AppErrorComponent },
        { path: 'accessdenied', component: AppAccessdeniedComponent },
        { path: '404', component: AppNotfoundComponent },
        { path: '**', redirectTo: '/404' },
    ]
},

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