Angular路由复用策略,如何仅从特定路由中重用?

4

我已经为我的应用配置了RouterReuseStrategy,看起来如下:

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


export class CustomRouteReuseStrategy implements RouteReuseStrategy {

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

    /**
     * Determines if this route (and its subtree) should be detached to be reused later
     */
    shouldDetach(route: ActivatedRouteSnapshot): boolean {

        if (!route.routeConfig || route.routeConfig.loadChildren) {
            return false;
        }
        /** Whether this route should be re used or not */
        let shouldReuse = false;
        if (route.routeConfig.data) {
            route.routeConfig.data.reuse ? shouldReuse = true : shouldReuse = false;
        }
        //Check the from route and decide whether to reuse or not
        if(route.routeConfig.path == 'page1') {
            shouldReuse = false;
        } else {
            shouldReuse = true;
        }
        return shouldReuse;
    }

    /**
     * Stores the detached route.
     */
    store(route: ActivatedRouteSnapshot, handler: DetachedRouteHandle): void {
        console.log('[router-reuse] storing handler');
        if (handler) {
            this.handlers[this.getUrl(route)] = handler;
        }
    }

    /**
     * Determines if this route (and its subtree) should be reattached
     * @param route Stores the detached route.
     */
    shouldAttach(route: ActivatedRouteSnapshot): boolean {
        return !!this.handlers[this.getUrl(route)];
    }

    /**
     * Retrieves the previously stored route
     */
    retrieve(route: ActivatedRouteSnapshot): DetachedRouteHandle {
        if (!route.routeConfig || route.routeConfig.loadChildren) {
            return null;
        }

        return this.handlers[this.getUrl(route)];
    }

    /**
     * Determines if a route should be reused
     */
    shouldReuseRoute(future: ActivatedRouteSnapshot, current: ActivatedRouteSnapshot): boolean {
        /** We only want to reuse the route if the data of the route config contains a reuse true boolean */
        let reUseUrl = false;

        if (future.routeConfig) {
            if (future.routeConfig.data) {
                reUseUrl = future.routeConfig.data.reuse;
            }
        }

        /**
         * Default reuse strategy by angular assers based on the following condition
         * @see https://github.com/angular/angular/blob/4.4.6/packages/router/src/route_reuse_strategy.ts#L67
         */
        const defaultReuse = (future.routeConfig === current.routeConfig);

        // If either of our reuseUrl and default Url are true, we want to reuse the route
        //
        return reUseUrl || defaultReuse;
    }

    /**
     * Returns a url for the current route
     */
    getUrl(route: ActivatedRouteSnapshot): string {
        /** The url we are going to return */
        let next = route;
        // Since navigation is usually relative
        // we go down to find out the child to be shown.
        while (next.firstChild) {
          next = next.firstChild;
        }
        let segments = '';
        // Then build a unique key-path by going to the root.
        while (next) {
          segments += next.url.join('/');
          next = next.parent;
        }
        return segments;
    }
}

在模块中的路由配置:
{ path: 'page1', component: Page1Component },
{ path: 'page2', component: Page2Component , data: {reuse: true}},
{ path: 'page3', component: Page3Component },

如您所见,对于page2组件,重用被设置为true,我希望仅当我从page3转到page2时才在page2组件中实现重用,而不是从page1page2

我已经在shouldDetach方法中进行更改,以检查来源路由并决定是否进行分离。但这似乎不起作用。我有遗漏吗?

1个回答

4
在我的路由复用设置中,我还有一个名为“reuseRoutesFrom”的字段。在我的情况下,我有一个列表和一个详细页面,因此当从详细页面返回到我的列表时,我想重用该列表,因此对于列表设置,我将会有以下内容:
{
        path: '',
        component: ListComponent,
        data: {
            shouldReuseRoute: true,
            reuseRoutesFrom: ['Detail', 'Detail/:Id']
        }
    },

在我的路由重用策略服务中,我会在 should attach 方法中看到类似这样的内容:
shouldAttach(route: ActivatedRouteSnapshot): boolean {

        var wasRoutePreviouslyDetached = !!this.handlers[route.url.join('/') || route.parent.url.join('/')];
        if (wasRoutePreviouslyDetached) {
            var reuseRouteFromVerified = route.data.reuseRoutesFrom.indexOf(this.routeLeftFrom) > -1;

            if (reuseRouteFromVerified) {

                return true;
            }
        }
        return false;
    }

当解除绑定时,我也将我离开的路线缓存起来,以便在上方使用:
    private routeLeftFrom: string;

    constructor() {}

    // Determines if this route (and its subtree) should be detached to be reused later.
    shouldDetach(route: ActivatedRouteSnapshot): boolean {
        // console.debug('CustomReuseStrategy:shouldDetach', route);
        this.routeLeftFrom = route.routeConfig.path;
        return route.data.shouldReuseRoute || false;
    }

这个能用吗?对我来说,当我从之前的目标返回到想要重复使用的页面时,'route.routeConfig.path'为空。 - Dibzmania
我目前正在使用Angular 9,这仍然有效。对于10和11,我不能确定。请记住,我在此处只发布了路由重用服务的一部分,因为原始帖子的作者已经拥有了其余部分的可工作版本。 - Kyle Anderson

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接