Pass query parameters to component service via routing

Discussão em 'Angular' iniciado por Fred2020, Outubro 23, 2024.

  1. Fred2020

    Fred2020 Guest

    Background


    • I have 2 routes with differing query params

      1) default route: '' (with query params id1)

      2) alternate route: 'alternate' (with query params id1, id2, id3)


    • These 2 routes will go to the same component.


    • That component has a service to fetch data


    • The service requires the params to fetch data


    • The service instance is DI'd in by routing

    export const MY_ROUTES: Routes = [
    {
    path: '',
    loadComponent: () =>
    import('./common.component').then((mod) => mod.CommonComponent),
    providers: [{ provide: AbstractService, useClass: Service1 }],
    },
    {
    path: 'alternate',
    loadComponent: () =>
    import('./common.component').then((mod) => mod.CommonComponent),
    providers: [{ provide: AbstractService, useClass: Service2 }],
    },
    ];


    Service1 and Service2 are derived from AbstractService which has a flexible enough signature for getData to allow for differing query param availability per route, id1 or id1, id2, id3

    export abstract class AbstractService {
    abstract getData(
    args: Partial<{ id1: string; id2: string; id3: string }>
    ): Observable<TheData[]>;
    }


    This works well. However I'd like to change the abstract class contract to simply expose an observable like below

    export abstract class AbstractService {
    abstract data$: Observable<TheData[]>;
    }


    The problem

    This introduces a problem. What is the best way now to provide the query parameter data to Service1 and Service2? Can I handle this by adding a constructor argument to Service1 and Service2 and resolving this somehow at the routing level using useFactory to generate the appropriate Service?

    Stackblitz

    Stackblitz demo

    Continue reading...

Compartilhe esta Página