Angular Router - 如何在 routerLink 更改时立即销毁旧组件

问题描述 投票:0回答:1

在 Angular 中,在

routerLink
触发路由更改后,旧组件只会在新组件初始化的同时基本被销毁: timeline of the Angular Router's default behaviour

这对我来说是一个问题,因为我想在旧的组件被销毁之后和新的组件构建之前显示一个旋转器——这在组件/模块延迟加载时是相关的。由于旧组件仅在构建新组件时才被销毁,因此我当前的旋转器只是在加载新组件时覆盖旧组件。 那么有没有办法配置路由器,以便在触发

routerLink

时立即销毁旧组件?像这样:

timeline of the behaviour I desire for the Angular Router in my use case
我还应该提到,我不想以任何方式隐藏 

router-outlet

,因为我还

将动画
应用到进入/离开组件,包括微调器。 如果重要的话,这就是代码的样子(它是

app.component

,顺便说一句,我正在使用 Tailwind):

@Component({
  styles: `
    :host ::ng-deep router-outlet + * { // target the routed components and the spinner
      &, & + * {
        @apply absolute top-0 left-0 w-full;
      }
    }
  `,
  animations: [
    trigger('routeAnimations', [
      transition('* <=> *', [
        query(':enter, :leave', [ style({
          position: 'absolute', left: 0, width: '100%', overflow: 'hidden',
        }) ], { optional: true }),
        group([
          query(':enter', [
            style({ opacity: '0' }),
            animate(animation, style({ opacity: '1' })),
          ], { optional: true }),
          query(':leave', [
            style({ opacity: '1' }),
            animate(animation, style({ opacity: '0' })),
          ], { optional: true }),
        ]),
      ]),
    ]),
  ],
})
export class MyComponent {
  #router = inject(Router);

  protected route = new Subject<string>();
  #lazyLoadingStarted$ = this.#router.events.pipe(
      filter(v => v instanceof RouteConfigLoadStart),
      map(() => '__lazy_loading__'),
  );
  protected routingState = toSignal(this.#lazyLoadingStarted$.pipe(mergeWith(this.route)));
}

<div [@routeAnimations]=routingState() class="relative h-full w-full">
    <router-outlet #outlet="outlet" (activate)="route.next(outlet.activatedRoute.snapshot.url[0]?.path || '')"/>
    @if (routingState() === '__lazy_loading__') {
        <div class="h-full">
            <div class="absolute-center">
                <mat-spinner/>
            </div>
        </div>
    }
</div>
更新

我当前的旋转器只是放在旧组件上

我找到了一个避免这个问题的小方法。基本上将旋转器的容器变成了覆盖层。只需更改样式和微调器的容器:

:host { @apply h-screen w-screen flex flex-col; .spinner-overlay, ::ng-deep router-outlet + * { // target the spinner and the routed components @apply absolute top-0 left-0 w-full; } .spinner-overlay { @apply h-full z-10; background: radial-gradient(hsla(0, 0%, 100%, 0.79), hsla(0, 0%, 100%, 0.17)); } }

<div class="spinner-overlay">
    <div class="absolute-center">
        <mat-spinner/>
    </div>
</div>
这意味着这个问题不再给我的用例带来问题,所以现在我只是出于好奇而寻找答案,因为可能还有其他用例,其中路由器行为的细粒度定制可能很重要。

angular angular-routing angular-animations angular-lazyloading
1个回答
0
投票
visibility: hidden

    

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.