Angular: Issues with Lazy loading different route modules for the same route based on condition

Viewed 571

I have an app that has a route called /opportunity/:id.

Depending on a value fetched from the API, I need to load different route modules for the above route. Say for Ex: If the opportunity is of type v2, load v2 module or if its v1, load v1 module.

Earlier: app.routing.ts

    {
        path: 'opportunity/:id',
        loadChildren: () => import('./content/opportunity/opportunity.module').then(m => m.OpportunityModule)
    },
    {
        path: 'opportunity-new/:id',
        loadChildren: () => import('./content/opportunity-v2/opportunity-v2.module').then(m => m.OpportunityV2Module)
    }, 

I am following this blog to achieve my goal - https://medium.com/@german.quinteros/angular-use-the-same-route-path-for-different-modules-or-components-11db75cac455 and this is how my code looks now.

Now: app.routing.ts

    {
        path: 'opportunity/:id',
        loadChildren: () => import('./modules/opportunity-route-handler.module').then(m => m.OpportunityRouteHandlerModule)
    }

opportunity-v2.module.ts:

import { OpportunityService } from './../services/opportunity.service';
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterModule, ROUTES, Routes, ActivatedRoute } from '@angular/router';

@NgModule({
  declarations: [],
  imports: [
    CommonModule,
    RouterModule
  ],
  providers: [
    {
      provide: ROUTES,
      useFactory: configOppHandlerRoutes,
      deps: [
        OpportunityService,
        ActivatedRoute
      ],
      multi: true
    }
  ]
})


export class OpportunityRouteHandlerModule {}

export function configOppHandlerRoutes(opportunityService: OpportunityService, router: ActivatedRoute) {
  let routes: Routes = [];
  opportunityService.checkOpportunityType().subscribe((data: boolean) => {
    if (data) {
    routes = [
      {
        path: '',
        loadChildren: () => import('./../content/opportunity/opportunity.module').then(m => m.OpportunityModule),
        resolve: { content: TranslationService }
      }
    ];
  } else {
    routes = [
      {
        path: '',
        loadChildren: () => import('./../content/opportunity-v2/opportunity-v2.module').then(m => m.OpportunityV2Module),
        resolve: { content: TranslationService }
      }
    ];
  }
  return routes;
  });
}

opportunity.service.ts:

import { map } from 'rxjs/operators';
import { ErrorService } from 'app/services/error.service';
import { AppApolloService } from 'app/services/app.apollo.service';
import { Injectable } from '@angular/core';
import { Router, ActivatedRoute, NavigationEnd, Event } from '@angular/router';
import { OpportunityQuery } from './opportunity.graphql';

@Injectable({
  providedIn: 'root'
})

export class OpportunityService {
  constructor(
    private activatedRoute: ActivatedRoute,
    private router: Router,
    private appApollo: AppApolloService,
    private errorService: ErrorService) {
  }

  public checkOpportunityType() {
    // this.activatedRoute.paramMap.subscribe((params: any) => {
    //   console.log('params', params);  // This returns empty params
    //   return true;
    // });
    // return this.activatedRoute.queryParamMap.subscribe(data => {
    //   console.log('data');  // This returns empty params
    // });
    return this.router.events.pipe(map(async (event: Event) => {
      let currentUrl;
      if (event instanceof NavigationEnd ) {
        currentUrl = event.url;    // value is '/opportunity/9432?apply=true'
        let oppId = currentUrl.split('/')[2].split('?')[0];  // very messy but works. Need better solution.
        return await this.getOpportunity(+oppId);
      }
    }));
  }

  getOpportunity(oppId) {
    return this.appApollo.query(OpportunityQuery, {id: oppId})
    .then((response: any) => {
      const opportunity = response.getOpportunity;
      if ((+opportunity.programme.id === 1) || (+opportunity.programme.id === 2) || (+opportunity.programme.id === 5)) {
        return true;
      } else {
        return false;
      }
    }, err => {
      this.errorService.error.next(true);
      this.errorService.errorDetails.next(err.networkError);
    });
  }
}

Now I have an issue here. I am unable to get :id param from the route using ActivatedRoute or ActivatedRouteSnapshot which led me to use router events. Is there a way I can get the route param without using router events?

I would also appreciate if anyone could suggest a better and more efficient way to achieve my goal. I found a couple of other alternative ways (https://medium.com/@lenseg1/loading-different-angular-modules-or-components-on-routes-with-same-path-2bb9ba4b6566) but they have their own issues like circular dependency etc., and the reason why I took this approach is because it looks cleaner.

1 Answers

Depending on a value fetched from the API

In Constructor of component where you get the value from API:

constructor(private route: Router) { }

And in method depending on value place your route url below:

this.route.navigateByUrl('/<set your url here>');
Related