2017-02-22 5 views
10

Я пытался использовать custom reuse strategy в моем angular2 проекте, , но я нашел, что это не работает с ленивой загрузки модуля. Кто знает об этом? Мой проект угловатые 2.6.4Angular2 не работает Выборочная Повторное использование стратегии с Ленивыми загрузками модуля

повторного-strategy.ts

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

export class CustomReuseStrategy implements RouteReuseStrategy { 

    handlers: {[key: string]: DetachedRouteHandle} = {}; 

    shouldDetach(route: ActivatedRouteSnapshot): boolean { 
     console.debug('CustomReuseStrategy:shouldDetach', route); 
     return true; 
    } 

    store(route: ActivatedRouteSnapshot, handle: DetachedRouteHandle): void { 
     console.debug('CustomReuseStrategy:store', route, handle); 
     this.handlers[route.routeConfig.path] = handle; 
    } 

    shouldAttach(route: ActivatedRouteSnapshot): boolean { 
     console.debug('CustomReuseStrategy:shouldAttach', route); 
     return !!route.routeConfig && !!this.handlers[route.routeConfig.path]; 
    } 

    retrieve(route: ActivatedRouteSnapshot): DetachedRouteHandle { 
     console.debug('CustomReuseStrategy:retrieve', route); 
     if (!route.routeConfig) return null; 
     return this.handlers[route.routeConfig.path]; 
    } 

    shouldReuseRoute(future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean { 
     console.debug('CustomReuseStrategy:shouldReuseRoute', future, curr); 
     return future.routeConfig === curr.routeConfig; 
    } 

} 

app.module.ts

const appRoutes: Routes = [ 
    { path: 'crisis-center', component: CrisisListComponent }, 
    { path: 'heroes', loadChildren: 'app/hero-list.module#HeroListModule' }, 
    { path: '', redirectTo: '/crisis-center', pathMatch: 'full' } 
]; 
@NgModule({ 
    imports: [ ... ], 
    declarations: [ ... ], 
    providers:[ 
    {provide: RouteReuseStrategy, useClass: CustomReuseStrategy} 
    ], 
    bootstrap: [ AppComponent ] 
}) 
export class AppModule { } 

и я поставил <input> как к компоненту, и я испытал его.

значение ввода в CrisisListComponent сохраняется, но значение HeroListComponent lazy-loaded не сохраняется.

Я не знаю, что он еще не поддерживается. Спасибо, что помогли мне.

ответ

7

RouteReuseStrategy действительно работает с компонентами LazyLoaded.

Проблема заключается в том, что вы используете route.routeConfig.path в качестве ключа для хранения и извлечения ручек.

Я не знаю, почему, но с LazyLoaded модулями, route.routeConfig.path пуст при выполнении shouldAttach

Решение, которое я использую, чтобы определить пользовательский ключ в моих маршрутов, как:

{ path: '...', loadChildren: '...module#...Module', data: { key: 'custom_key' } } 

Этот значение ключа можно легко получить доступ в ActivatedRouteSnapshot, как:

route.data.key 

с помощью этой кнопки вы можете хранить и извлекать ручку правильно.

0

использование этого ReuseStrategy

import { ActivatedRouteSnapshot, DetachedRouteHandle, RouteReuseStrategy } from '@angular/router'; 
export class CustomReuseStrategy implements RouteReuseStrategy { 

    private handlers: {[key: string]: DetachedRouteHandle} = {}; 


    constructor() { 

    } 

    shouldDetach(route: ActivatedRouteSnapshot): boolean { 
    return true; 
    } 

    store(route: ActivatedRouteSnapshot, handle: DetachedRouteHandle): void { 
    this.handlers[route.url.join("/") || route.parent.url.join("/")] = handle; 
    } 

    shouldAttach(route: ActivatedRouteSnapshot): boolean { 
    return !!this.handlers[route.url.join("/") || route.parent.url.join("/")]; 
    } 

    retrieve(route: ActivatedRouteSnapshot): DetachedRouteHandle { 
    return this.handlers[route.url.join("/") || route.parent.url.join("/")]; 
    } 

    shouldReuseRoute(future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean { 
    return future.routeConfig === curr.routeConfig; 
    } 

} 
1

использовать этот обычай Многократное стратегия файл для ленивых загрузки модуля

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

/** Interface for object which can store both: 
* An ActivatedRouteSnapshot, which is useful for determining whether or not you should attach a route (see this.shouldAttach) 
* A DetachedRouteHandle, which is offered up by this.retrieve, in the case that you do want to attach the stored route 
*/ 
interface RouteStorageObject { 
    snapshot: ActivatedRouteSnapshot; 
    handle: DetachedRouteHandle; 
} 

export class CustomReuseStrategy implements RouteReuseStrategy { 

    handlers: {[key: string]: DetachedRouteHandle} = {}; 

    shouldDetach(route: ActivatedRouteSnapshot): boolean { 
     console.debug('CustomReuseStrategy:shouldDetach', route); 
     return !!route.data && !!(route.data as any).shouldDetach; 
    } 

    store(route: ActivatedRouteSnapshot, handle: DetachedRouteHandle): void { 
     console.debug('CustomReuseStrategy:store', route, handle); 
     this.handlers[route.data['key']]= handle; 
    } 

    shouldAttach(route: ActivatedRouteSnapshot): boolean { 
     console.debug('CustomReuseStrategy:shouldAttach', route); 
     return !!route.data && !!this.handlers[route.data['key']]; 
    } 

    retrieve(route: ActivatedRouteSnapshot): DetachedRouteHandle { 
     console.debug('CustomReuseStrategy:retrieve', route); 
     if (!route.data) return null; 
     return this.handlers[route.data['key']]; 
    } 

    shouldReuseRoute(future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean { 
     console.debug('CustomReuseStrategy:shouldReuseRoute', future, curr); 
     return future.data === curr.data; 
    } 

} 
0

Используйте этот один. Он использует имя компонента в качестве ключа для хранения и извлечения дескрипторов.

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

export class CustomReuseStrategy implements RouteReuseStrategy { 


    handlers: { [key: string]: DetachedRouteHandle } = {}; 


    shouldDetach(route: ActivatedRouteSnapshot): boolean { 
    return true; 
    } 

    store(route: ActivatedRouteSnapshot, handle: DetachedRouteHandle): void { 
    this.handlers[this.getKey(route)] = handle; 
    } 

    shouldAttach(route: ActivatedRouteSnapshot): boolean { 
    return !!route.routeConfig && !!this.handlers[this.getKey(route)]; 
    } 

    retrieve(route: ActivatedRouteSnapshot): DetachedRouteHandle { 
    if (!route.routeConfig) { 
     return null; 
    } 
    return this.handlers[this.getKey(route)]; 
    } 

    shouldReuseRoute(future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean { 
    return curr.routeConfig === future.routeConfig; 
    } 

    private getKey(route: ActivatedRouteSnapshot) { 
    let key: string; 
    if (route.component) { 
     key = route.component['name']; 
    } else { 
     key = route.firstChild.component['name']; 
    } 
    return key; 
    } 

} 
Смежные вопросы