RouteReuseStrategy和Lazy加载角度

时间:2017-12-08 10:28:32

标签: javascript angular angular2-routing

我有多个模块,它们在延迟加载,我正在尝试使用RouteReuseStrategy。

目前我能够获得我想要的功能并重新使用路线,除了情况。我有一个列表显示在主页上,当我尝试单击列表项时,我收到此错误: TypeError:无法读取未定义的属性'instance'

调试时我注意到在页面后我应该看到加载它然后转到'shouldDetach',它返回true,然后删除页面内容并显示上面的错误。

我的问题是CustomReuseStrategy中的方法执行的顺序是什么,所以我可以阻止它在加载后被删除。

这是我的班级:

export class CustomReuseStrategy implements RouteReuseStrategy {

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

constructor() {}

public calcKey(route: ActivatedRouteSnapshot) {
    let next = route;
    while (next.firstChild) {
        next = next.firstChild;
    }
    const segments: string[] = [];
    while (next) {
        segments.push(next.url.join("/"));
        next = next.parent;
    }
    let url = segments.reverse().join("/");
    return url;
}
/**
 * Determines if this route (and its subtree) should be detached to be reused later.
 */
public shouldDetach(route: ActivatedRouteSnapshot): boolean {
    //console.debug('CustomReuseStrategy:shouldDetach', route);
    return true;
}
/**
* Stores the detached route.
*/
public store(route: ActivatedRouteSnapshot, handle: DetachedRouteHandle): void {
    //console.debug('CustomReuseStrategy:store', route, handle);
    this.handlers[this.calcKey(route)] = handle;
}
/**
* Determines if this route (and its subtree) should be reattached.
*/
public shouldAttach(route: ActivatedRouteSnapshot): boolean {
    //console.debug('CustomReuseStrategy:shouldAttach', route);
    return !!route.routeConfig && !!this.handlers[this.calcKey(route)];
}
/**
 * Retrieves the previously stored route.
 */
public retrieve(route: ActivatedRouteSnapshot): DetachedRouteHandle {
    //console.debug('CustomReuseStrategy:retrieve', route);
    if (!route.routeConfig) {
        return null;
    }
    return this.handlers[this.calcKey(route)]; 

}
/**
* Determines if a route should be reused.
*/
public shouldReuseRoute(future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean {
    //console.debug('CustomReuseStrategy:shouldReuseRoute', future, curr);
    return this.calcKey(curr) === this.calcKey(future);
}
}

非常感谢这方面的帮助。

0 个答案:

没有答案