Стратегия повторного использования маршрутизатора - PullRequest
0 голосов
/ 03 июля 2019

Я пытаюсь сохранить данные компонента, когда пользователь закрывает / обновляет вкладку или (нажимает назад / вперед), используя стратегию повторного использования маршрутизатора, но после добавления поставщика CustomReuseStrategy routerLink перестал работать правильно.

После входа в систему мы перенаправленыв '/ dashboard / begin', а затем, если я пытаюсь перейти через / router> / dashboard / search 'или' / dashboard / 123 'через routerLink, компонент не изменяется

Однако URL прямого доступа работает хорошо

Кто-нибудь когда-либо испытывал это?

app.module.ts

@NgModule({
  providers: [
    AuthGuard,
    {
      provide: RouteReuseStrategy,
      useClass: CustomReuseStrategy
    }]
})

app.routing.ts

 const ROUTES: Routes = [
      { path: 'dashboard', loadChildren: './dashboard/dashboard.module#DashboardModule', canActivateChild: [AuthGuard]},
      { path: 'login', component: LoginComponent },
      { path: '', redirectTo: '/login', pathMatch: 'full' }
]

dashboard.routing.ts

const DASHBOARD_ROUTES: Routes = [
  {
    path: '', component: DashboardComponent,
    children: [
      {
        path: 'begin',
        component: BeginListComponent,
      },
      {
        path: 'search',
        children: [
          {path: '', component: SearchListComponent },
          {path: ':id', component: SearchIdComponent}
        ]
      }
   }
 ]

custom.reuse.strategy.ts

import { ActivatedRouteSnapshot, DetachedRouteHandle, RouteReuseStrategy } from '@angular/router';

export class CustomReuseStrategy implements RouteReuseStrategy {
  public static handlers: { [key: string]: DetachedRouteHandle } = {};

  private static waitDelete: string;

  public static deleteRouteSnapshots(): void {
    CustomReuseStrategy.handlers = {};
  }

  public static deleteRouteSnapshot(name: string): void {
    if (CustomReuseStrategy.handlers[name]) {
      delete CustomReuseStrategy.handlers[name];
    } else {
      CustomReuseStrategy.waitDelete = name;
    }
  }

  public shouldDetach(route: ActivatedRouteSnapshot): boolean {
    console.log(route);
    if (!route) {
      CustomReuseStrategy.deleteRouteSnapshots();
      return false;
    }
    if (route.params && Object.keys(route.params).length > 0) {
      return false; 
    }
    return true;
  }

  public store(route: ActivatedRouteSnapshot, handle: DetachedRouteHandle): void {
    if (
      CustomReuseStrategy.waitDelete &&
      CustomReuseStrategy.waitDelete === this.getRouteUrl(route)
    ) {
      CustomReuseStrategy.waitDelete = null;
      return;
    }
    CustomReuseStrategy.handlers[this.getRouteUrl(route)] = handle;
  }

  public shouldAttach(route: ActivatedRouteSnapshot): boolean {
    return !!CustomReuseStrategy.handlers[this.getRouteUrl(route)];
  }


  public retrieve(route: ActivatedRouteSnapshot): DetachedRouteHandle {
    if (!route.routeConfig) {
      return null;
    }

    return CustomReuseStrategy.handlers[this.getRouteUrl(route)];
  }

  public shouldReuseRoute(future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean {
    return (
      future.routeConfig === curr.routeConfig &&
      JSON.stringify(future.params) === JSON.stringify(curr.params)
    );
  }

  private getRouteUrl(route: ActivatedRouteSnapshot) {
    return route['_routerState'].url.replace(/\//g, '_');
  }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...