angularangular-router

angular Router reuse strategy custom class - inject service


I need to track components that are currently have been detached. I am thinking to use a service for that. I am trying to inject that service into the custom strategy class but, since it does not have a constructor, I don't see a way of doing it. Any idea?


Solution

  • You should be able to add a constructor as long as you call super() (like any other extends class). Otherwise the inject() function should also work (if you're in Angular 17 or newer) and avoids a child constructor.

    With a service like so:

    import { Injectable } from '@angular/core';
    
    @Injectable({
      providedIn: 'root',
    })
    export class DetachedComponentTrackingService { }
    

    The strategy would look similar to:

    import { inject } from '@angular/core';
    import { 
      ActivatedRouteSnapshot, 
      RouteReuseStrategy 
    } from '@angular/router';
    import { 
      DetachedComponentTrackingService 
    } from './.../detached-component-tracking.service';
    
    export class DetachedAwareRouteReuseStrategy 
      extends RouteReuseStrategy {
    
      private readonly functionInjectedService =
        inject(DetachedComponentTrackingService);
    
      constructor(
        private readonly constructorInjectedService: DetachedComponentTrackingService
      ) { 
        // RouteReuseStrategy
        super();
      }
    
      override shouldDetach(route: ActivatedRouteSnapshot): boolean {
        // this.functionInjectedService...
        // this.constructorInjectedService...
        throw new Error('Method not implemented.');
      }
    
      // Other overrides...
    }
    

    Then just provide the strategy like any other provider token:

    import { AppComponent } from './.../app.component';
    import { RouteReuseStrategy } from '@angular/router';
    import { 
      DetachedComponentTrackingService 
    } from './.../detached-component-tracking.service';
    import { 
      DetachedAwareRouteReuseStrategy 
    } from './.../detached-aware-route-reuse-strategy';
    
    bootstrapApplication(AppComponent, {
      providers: [
        {
          provide: RouteReuseStrategy,
          useClass: DetachedAwareRouteReuseStrategy,
        },
        provideRouter([
          // Routes...
        ]),
      ],
    });
    

    There's a section of the providers documentation that covers useClass with dependencies and I'm not seeing any special considerations there.