1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.
  2. Anuncie Aqui
    Anuncie aqui você Também: fdantas@4each.com.br

How to inject RouteReuseStrategy only in specific components?

Discussão em 'Angular' iniciado por Andrei Manolache, Setembro 26, 2024.

  1. In my Angular16 standalone app I want to implement a RouteReuseStrategy and add it only to specific components. I found some solutions that implied using some extras (eg https://stackoverflow.com/a/49156005/11615575), but I would like a different approach.

    Given this implementation:

    @Injectable({
    providedIn: 'root'
    })
    export class AlwaysReloadRouteStrategy implements RouteReuseStrategy {
    retrieve(route: ActivatedRouteSnapshot): DetachedRouteHandle | null {
    return null; // return null, meaning no route will be reused
    }

    shouldAttach(route: ActivatedRouteSnapshot): boolean {
    return false; // don't attach any stored route, force reload
    }

    shouldDetach(route: ActivatedRouteSnapshot): boolean {
    return false; // never detach the route, we want to force a reload
    }

    shouldReuseRoute(
    future: ActivatedRouteSnapshot,
    curr: ActivatedRouteSnapshot
    ): boolean {
    return false; // don't reuse any route, always reload
    }

    store(
    route: ActivatedRouteSnapshot,
    handle: DetachedRouteHandle | null
    ): void {
    // don't story any route
    }
    }


    When trying to use it directly on the component:

    @Component({
    selector: 'app-configuration-general',
    standalone: true,
    imports: [
    CommonModule,
    RouterLink,
    ReactiveFormsModule,
    ],
    providers: [
    { provide: RouteReuseStrategy, useClass: AlwaysReloadRouteStrategy } <---- injecting it here
    ],
    templateUrl: './configuration-general.component.html'
    })
    export class ConfigurationGeneralComponent implements OnInit, OnDestroy {
    constructor(
    private readonly router: Router,
    private readonly fb: FormBuilder
    ) {}

    onClick(): void {
    this.router.navigate([this.router.url], { onSameUrlNavigation: 'reload'}); <--- does not work
    }
    }


    However, if instead of adding it at component level I do it inside main.ts like this (so basically it's applied to all routes), it works successfully:

    bootstrapApplication(AppComponent, {
    providers: [
    ...
    provideRouter(ROUTES, withPreloading(PreloadAllModules), ),
    { provide: RouteReuseStrategy, useClass: AlwaysReloadRouteStrategy }, <--- here

    UPDATE

    Noticed that for the first approach, if I update the `router` instance then the reload works:
    ngOnInit(): void {
    this.router.routeReuseStrategy = new AlwaysReloadRouteStrategy();
    }

    Continue reading...

Compartilhe esta Página