如何在 Angular 2 中为特定路由实现 RouteReuseStrategy shouldDetach

How to implement RouteReuseStrategy shouldDetach for specific routes in Angular 2

我有一个 Angular 2 模块,我在其中实现了路由,并希望在导航时存储状态。
用户应该能够:

  1. 使用 'search formula'
  2. 搜索文档
  3. 导航到其中一个结果
  4. 导航回 'searchresult' - 不与服务器通信

这是可能的,包括 RouteReuseStrategy
问题是:
如何实现不存储文档?

所以不应存储路由路径“文档”'s state should be stored and the route path "documents/:id"' 状态?

嘿安德斯,问得好!

我和你有几乎相同的用例,并且想做同样的事情!用户搜索 > 获取结果 > 用户导航到结果 > 用户导航返回 > BOOM 快速 return 到结果,但你没有不想存储用户导航到的特定结果。

tl;dr

您需要有一个 class 实现 RouteReuseStrategy 并在 ngModule 中提供您的策略。如果要在存储路由时修改,修改shouldDetach函数。当它returns true,Angular存储路由。如果想在附加路由时修改,修改shouldAttach函数。当 shouldAttach return 为真时,Angular 将使用存储的路由代替请求的路由。这里有一个 Plunker 供你玩。

关于 RouteReuseStrategy

通过问这个问题,你已经明白 RouteReuseStrategy 允许你告诉 Angular 不是 销毁组件,但实际上保存它以备重新使用稍后渲染。这很酷,因为它允许:

  • 减少 服务器调用
  • 增加速度
  • AND 默认情况下,组件呈现的状态与离开时相同

最后一个很重要,如果你想暂时离开一个页面,即使用户输入了 很多 文本。企业应用程序会喜欢此功能,因为 过多 的表单数量!

这就是我想出的解决问题的办法。正如您所说,您需要利用@angular/router 在 3.4.1 及更高版本中提供的 RouteReuseStrategy

待办事项

首先确保你的项目有@angular/router版本3.4.1或更高版本。

下一步,创建一个文件来存放实现RouteReuseStrategy 的class。我调用了我的 reuse-strategy.ts 并将其放在 /app 文件夹中以便妥善保管。现在,这个 class 应该是这样的:

import { RouteReuseStrategy } from '@angular/router';

export class CustomReuseStrategy implements RouteReuseStrategy {
}

(不用担心您的 TypeScript 错误,我们即将解决所有问题)

通过向您的 app.module 提供 class 来完成基础工作。请注意,您还没有写 CustomReuseStrategy,但应该继续 import 它仍然来自 reuse-strategy.ts。还有import { RouteReuseStrategy } from '@angular/router';

@NgModule({
    [...],
    providers: [
        {provide: RouteReuseStrategy, useClass: CustomReuseStrategy}
    ]
)}
export class AppModule {
}

最后一部分 正在编写 class,它将控制路由是否分离、存储、检索和重新附加。在我们开始讨论旧的 copy/paste 之前,我将在这里根据我的理解对机制做一个简短的解释。我描述的方法请参考下面的代码,当然,代码.

中有很多文档
  1. 导航时,shouldReuseRoute 触发。这个对我来说有点奇怪,但如果它 returns true,那么它实际上会重用你当前所在的路线,并且 none 其他方法被触发。如果用户正在离开,我只是 return false。
  2. 如果 shouldReuseRoute returns false, shouldDetach 触发。 shouldDetach 确定是否要存储路线,return 是一个 boolean 表示。 这是你应该决定store/not存储路径的地方,我会通过检查你想要存储的路径数组来做到这一点route.routeConfig.path,如果数组中不存在 path,return 则为 false。
  3. 如果 shouldDetach returns truestore 被触发,这是您存储任何您想要的关于路线的信息的机会。无论你做什么,你都需要存储 DetachedRouteHandle 因为那是 Angular 稍后用来识别你存储的组件的东西。下面,我将 DetachedRouteHandleActivatedRouteSnapshot 都存储到我的 class.
  4. 的本地变量中

那么,我们已经了解了存储逻辑,但是如何导航 一个组件呢? Angular 如何决定截取您的导航并将存储的导航放回原来的位置?

  1. 同样,在 shouldReuseRoute 已 returned false 运行后,shouldAttach 运行,这是您确定是否要重新生成或使用组件的机会记忆。如果您想重用存储的组件,return true 就可以了!
  2. 现在 Angular 将询问您,"which component do you want us to use?",您将通过 returning 来自 retrieve 的那个组件的 DetachedRouteHandle 来表示。

这就是您需要的几乎所有逻辑!在下面 reuse-strategy.ts 的代码中,我还为您提供了一个比较两个对象的漂亮函数。我用它来比较未来路线的 route.paramsroute.queryParams 与存储的路线。如果这些都匹配,我想使用存储的组件而不是生成一个新组件。但具体如何 取决于您!

重用-strategy.ts

/**
 * reuse-strategy.ts
 * by corbfon 1/6/17
 */

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 {

    /** 
     * Object which will store RouteStorageObjects indexed by keys
     * The keys will all be a path (as in route.routeConfig.path)
     * This allows us to see if we've got a route stored for the requested path
     */
    storedRoutes: { [key: string]: RouteStorageObject } = {};

    /** 
     * Decides when the route should be stored
     * If the route should be stored, I believe the boolean is indicating to a controller whether or not to fire this.store
     * _When_ it is called though does not particularly matter, just know that this determines whether or not we store the route
     * An idea of what to do here: check the route.routeConfig.path to see if it is a path you would like to store
     * @param route This is, at least as I understand it, the route that the user is currently on, and we would like to know if we want to store it
     * @returns boolean indicating that we want to (true) or do not want to (false) store that route
     */
    shouldDetach(route: ActivatedRouteSnapshot): boolean {
        let detach: boolean = true;
        console.log("detaching", route, "return: ", detach);
        return detach;
    }

    /**
     * Constructs object of type `RouteStorageObject` to store, and then stores it for later attachment
     * @param route This is stored for later comparison to requested routes, see `this.shouldAttach`
     * @param handle Later to be retrieved by this.retrieve, and offered up to whatever controller is using this class
     */
    store(route: ActivatedRouteSnapshot, handle: DetachedRouteHandle): void {
        let storedRoute: RouteStorageObject = {
            snapshot: route,
            handle: handle
        };

        console.log( "store:", storedRoute, "into: ", this.storedRoutes );
        // routes are stored by path - the key is the path name, and the handle is stored under it so that you can only ever have one object stored for a single path
        this.storedRoutes[route.routeConfig.path] = storedRoute;
    }

    /**
     * Determines whether or not there is a stored route and, if there is, whether or not it should be rendered in place of requested route
     * @param route The route the user requested
     * @returns boolean indicating whether or not to render the stored route
     */
    shouldAttach(route: ActivatedRouteSnapshot): boolean {

        // this will be true if the route has been stored before
        let canAttach: boolean = !!route.routeConfig && !!this.storedRoutes[route.routeConfig.path];

        // this decides whether the route already stored should be rendered in place of the requested route, and is the return value
        // at this point we already know that the paths match because the storedResults key is the route.routeConfig.path
        // so, if the route.params and route.queryParams also match, then we should reuse the component
        if (canAttach) {
            let willAttach: boolean = true;
            console.log("param comparison:");
            console.log(this.compareObjects(route.params, this.storedRoutes[route.routeConfig.path].snapshot.params));
            console.log("query param comparison");
            console.log(this.compareObjects(route.queryParams, this.storedRoutes[route.routeConfig.path].snapshot.queryParams));

            let paramsMatch: boolean = this.compareObjects(route.params, this.storedRoutes[route.routeConfig.path].snapshot.params);
            let queryParamsMatch: boolean = this.compareObjects(route.queryParams, this.storedRoutes[route.routeConfig.path].snapshot.queryParams);

            console.log("deciding to attach...", route, "does it match?", this.storedRoutes[route.routeConfig.path].snapshot, "return: ", paramsMatch && queryParamsMatch);
            return paramsMatch && queryParamsMatch;
        } else {
            return false;
        }
    }

    /** 
     * Finds the locally stored instance of the requested route, if it exists, and returns it
     * @param route New route the user has requested
     * @returns DetachedRouteHandle object which can be used to render the component
     */
    retrieve(route: ActivatedRouteSnapshot): DetachedRouteHandle {

        // return null if the path does not have a routerConfig OR if there is no stored route for that routerConfig
        if (!route.routeConfig || !this.storedRoutes[route.routeConfig.path]) return null;
        console.log("retrieving", "return: ", this.storedRoutes[route.routeConfig.path]);

        /** returns handle when the route.routeConfig.path is already stored */
        return this.storedRoutes[route.routeConfig.path].handle;
    }

    /** 
     * Determines whether or not the current route should be reused
     * @param future The route the user is going to, as triggered by the router
     * @param curr The route the user is currently on
     * @returns boolean basically indicating true if the user intends to leave the current route
     */
    shouldReuseRoute(future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean {
        console.log("deciding to reuse", "future", future.routeConfig, "current", curr.routeConfig, "return: ", future.routeConfig === curr.routeConfig);
        return future.routeConfig === curr.routeConfig;
    }

    /** 
     * This nasty bugger finds out whether the objects are _traditionally_ equal to each other, like you might assume someone else would have put this function in vanilla JS already
     * One thing to note is that it uses coercive comparison (==) on properties which both objects have, not strict comparison (===)
     * Another important note is that the method only tells you if `compare` has all equal parameters to `base`, not the other way around
     * @param base The base object which you would like to compare another object to
     * @param compare The object to compare to base
     * @returns boolean indicating whether or not the objects have all the same properties and those properties are ==
     */
    private compareObjects(base: any, compare: any): boolean {

        // loop through all properties in base object
        for (let baseProperty in base) {

            // determine if comparrison object has that property, if not: return false
            if (compare.hasOwnProperty(baseProperty)) {
                switch(typeof base[baseProperty]) {
                    // if one is object and other is not: return false
                    // if they are both objects, recursively call this comparison function
                    case 'object':
                        if ( typeof compare[baseProperty] !== 'object' || !this.compareObjects(base[baseProperty], compare[baseProperty]) ) { return false; } break;
                    // if one is function and other is not: return false
                    // if both are functions, compare function.toString() results
                    case 'function':
                        if ( typeof compare[baseProperty] !== 'function' || base[baseProperty].toString() !== compare[baseProperty].toString() ) { return false; } break;
                    // otherwise, see if they are equal using coercive comparison
                    default:
                        if ( base[baseProperty] != compare[baseProperty] ) { return false; }
                }
            } else {
                return false;
            }
        }

        // returns true only after false HAS NOT BEEN returned through all loops
        return true;
    }
}

行为

此实现将用户在路由器上访问的每条唯一路由恰好存储一次。这将在整个用户在站点上的会话期间继续添加到存储在内存中的组件。如果您想限制存储的路线,可以使用 shouldDetach 方法。它控制您保存的路线。

例子

假设您的用户从主页搜索某些内容,这会将他们导航到路径 search/:term,该路径可能看起来像 www.yourwebsite.com/search/thingsearchedfor。搜索页面包含一堆搜索结果。你想存储这条路线,以防他们想回来!现在他们单击搜索结果并导航到 view/:resultId,您 不想 存储它,因为它们可能只存在一次。有了上面的实现,我会简单地改变 shouldDetach 方法!它可能是这样的:

首先让我们创建一个要存储的路径数组。

private acceptedRoutes: string[] = ["search/:term"];

现在,在 shouldDetach 中,我们可以根据数组检查 route.routeConfig.path

shouldDetach(route: ActivatedRouteSnapshot): boolean {
    // check to see if the route's path is in our acceptedRoutes array
    if (this.acceptedRoutes.indexOf(route.routeConfig.path) > -1) {
        console.log("detaching", route);
        return true;
    } else {
        return false; // will be "view/:resultId" when user navigates to result
    }
}

因为Angular将只存储一个路由实例,这种存储将是轻量级的,我们将只存储位于[=55的组件=] 而不是所有其他人!

其他链接

虽然目前还没有太多文档,但这里有几个链接指向现有的文档:

Angular 文档:https://angular.io/docs/ts/latest/api/router/index/RouteReuseStrategy-class.html

介绍文章:https://www.softwarearchitekt.at/post/2016/12/02/sticky-routes-in-angular-2-3-with-routereusestrategy.aspx

nativescript-angular对RouteReuseStrategy的默认实现:https://github.com/NativeScript/nativescript-angular/blob/cb4fd3a/nativescript-angular/router/ns-route-reuse-strategy.ts

不要被已接受的答案吓倒,这非常简单。这是您需要的快速答案。我建议至少阅读已接受的答案,因为它包含很多细节。

此解决方案不像已接受的答案那样进行任何参数比较,但它可以很好地存储一组路由。

app.module.ts 进口:

import { RouteReuseStrategy } from '@angular/router';
import { CustomReuseStrategy, Routing } from './shared/routing';

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

shared/routing.ts:

export class CustomReuseStrategy implements RouteReuseStrategy {
 routesToCache: string[] = ["dashboard"];
 storedRouteHandles = new Map<string, DetachedRouteHandle>();

 // Decides if the route should be stored
 shouldDetach(route: ActivatedRouteSnapshot): boolean {
    return this.routesToCache.indexOf(route.routeConfig.path) > -1;
 }

 //Store the information for the route we're destructing
 store(route: ActivatedRouteSnapshot, handle: DetachedRouteHandle): void {
    this.storedRouteHandles.set(route.routeConfig.path, handle);
 }

//Return true if we have a stored route object for the next route
 shouldAttach(route: ActivatedRouteSnapshot): boolean {
    return this.storedRouteHandles.has(route.routeConfig.path);
 }

 //If we returned true in shouldAttach(), now return the actual route data for restoration
 retrieve(route: ActivatedRouteSnapshot): DetachedRouteHandle {
    return this.storedRouteHandles.get(route.routeConfig.path);
 }

 //Reuse the route if we're going to and from the same route
 shouldReuseRoute(future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean {
    return future.routeConfig === curr.routeConfig;
 }
}

要将 Chris Fremgen 的策略用于延迟加载的模块,请将 CustomReuseStrategy class 修改为以下内容:

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

export class CustomReuseStrategy implements RouteReuseStrategy {
  routesToCache: string[] = ["company"];
  storedRouteHandles = new Map<string, DetachedRouteHandle>();

  // Decides if the route should be stored
  shouldDetach(route: ActivatedRouteSnapshot): boolean {
     return this.routesToCache.indexOf(route.data["key"]) > -1;
  }

  //Store the information for the route we're destructing
  store(route: ActivatedRouteSnapshot, handle: DetachedRouteHandle): void {
     this.storedRouteHandles.set(route.data["key"], handle);
  }

  //Return true if we have a stored route object for the next route
  shouldAttach(route: ActivatedRouteSnapshot): boolean {
     return this.storedRouteHandles.has(route.data["key"]);
  }

  //If we returned true in shouldAttach(), now return the actual route data for restoration
  retrieve(route: ActivatedRouteSnapshot): DetachedRouteHandle {
     return this.storedRouteHandles.get(route.data["key"]);
  }

  //Reuse the route if we're going to and from the same route
  shouldReuseRoute(future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean {
     return future.routeConfig === curr.routeConfig;
  }
}

最后,在您的功能模块的路由文件中,定义您的密钥:

{ path: '', component: CompanyComponent, children: [
    {path: '', component: CompanyListComponent, data: {key: "company"}},
    {path: ':companyID', component: CompanyDetailComponent},
]}

更多信息here

以下是作品!参考:https://www.cnblogs.com/lovesangel/p/7853364.html

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

export class CustomReuseStrategy implements RouteReuseStrategy {

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

    private static waitDelete: string

    public static deleteRouteSnapshot(name: string): void {
        if (CustomReuseStrategy.handlers[name]) {
            delete CustomReuseStrategy.handlers[name];
        } else {
            CustomReuseStrategy.waitDelete = name;
        }
    }
   
    public shouldDetach(route: ActivatedRouteSnapshot): boolean {
        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)]
    }

    /** 从缓存中获取快照,若无则返回nul */
    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, '_')
    }
}

除了已接受的答案(由 Corbfon 提供)和 Chris Fremgen 的更短更直接的解释之外,我想添加一种更灵活的处理路由的方式,应该使用重用策略。

两个答案都是将我们要缓存的路由存储在一个数组中,然后检查当前路由路径是否在数组中。此检查在 shouldDetach 方法中完成。

我发现这种方法不灵活,因为如果我们想更改路由名称,我们需要记住还要更改 CustomReuseStrategy class 中的路由名称。我们可能忘记更改它,或者我们团队中的其他一些开发人员可能决定更改路由名称,甚至不知道 RouteReuseStrategy.

的存在

不是将我们要缓存的路由存储在数组中,我们可以使用data对象直接在RouterModule中标记它们。这样即使我们更改路由名称,重用策略仍然会应用。

{
  path: 'route-name-i-can-change',
  component: TestComponent,
  data: {
    reuseRoute: true
  }
}

然后在 shouldDetach 方法中我们使用它。

shouldDetach(route: ActivatedRouteSnapshot): boolean {
  return route.data.reuseRoute === true;
}

另一个更有效、更完整和可重用的实现。这个支持延迟加载模块,如@Uğur Dinç 并集成@Davor 路由数据标志。最好的改进是基于页面绝对路径自动生成(几乎)唯一标识符。这样你就不用在每个页面都自己定义了。

标记要缓存设置的任何页面reuseRoute: true。它将在 shouldDetach 方法中使用。

{
  path: '',
  component: MyPageComponent,
  data: { reuseRoute: true },
}

这是最简单的策略实现,没有比较查询参数。

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

export class CustomReuseStrategy implements RouteReuseStrategy {

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

  shouldDetach(route: ActivatedRouteSnapshot): boolean {
    return route.data.reuseRoute || false;
  }

  store(route: ActivatedRouteSnapshot, handle: DetachedRouteHandle): void {
    const id = this.createIdentifier(route);
    if (route.data.reuseRoute) {
      this.storedHandles[id] = handle;
    }
  }

  shouldAttach(route: ActivatedRouteSnapshot): boolean {
    const id = this.createIdentifier(route);
    const handle = this.storedHandles[id];
    const canAttach = !!route.routeConfig && !!handle;
    return canAttach;
  }

  retrieve(route: ActivatedRouteSnapshot): DetachedRouteHandle {
    const id = this.createIdentifier(route);
    if (!route.routeConfig || !this.storedHandles[id]) return null;
    return this.storedHandles[id];
  }

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

  private createIdentifier(route: ActivatedRouteSnapshot) {
    // Build the complete path from the root to the input route
    const segments: UrlSegment[][] = route.pathFromRoot.map(r => r.url);
    const subpaths = ([] as UrlSegment[]).concat(...segments).map(segment => segment.path);
    // Result: ${route_depth}-${path}
    return segments.length + '-' + subpaths.join('/');
  }
}

这个也比较查询参数。 compareObjects 比@Corbfon 版本略有改进:遍历基础对象和比较对象的属性。请记住,您可以使用更可靠的外部实现,如 lodash isEqual 方法。

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

interface RouteStorageObject {
  snapshot: ActivatedRouteSnapshot;
  handle: DetachedRouteHandle;
}

export class CustomReuseStrategy implements RouteReuseStrategy {

  storedRoutes: { [key: string]: RouteStorageObject } = {};

  shouldDetach(route: ActivatedRouteSnapshot): boolean {
    return route.data.reuseRoute || false;
  }

  store(route: ActivatedRouteSnapshot, handle: DetachedRouteHandle): void {
    const id = this.createIdentifier(route);
    if (route.data.reuseRoute && id.length > 0) {
      this.storedRoutes[id] = { handle, snapshot: route };
    }
  }

  shouldAttach(route: ActivatedRouteSnapshot): boolean {
    const id = this.createIdentifier(route);
    const storedObject = this.storedRoutes[id];
    const canAttach = !!route.routeConfig && !!storedObject;
    if (!canAttach) return false;

    const paramsMatch = this.compareObjects(route.params, storedObject.snapshot.params);
    const queryParamsMatch = this.compareObjects(route.queryParams, storedObject.snapshot.queryParams);

    console.log('deciding to attach...', route, 'does it match?');
    console.log('param comparison:', paramsMatch);
    console.log('query param comparison', queryParamsMatch);
    console.log(storedObject.snapshot, 'return: ', paramsMatch && queryParamsMatch);

    return paramsMatch && queryParamsMatch;
  }

  retrieve(route: ActivatedRouteSnapshot): DetachedRouteHandle {
    const id = this.createIdentifier(route);
    if (!route.routeConfig || !this.storedRoutes[id]) return null;
    return this.storedRoutes[id].handle;
  }

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

  private createIdentifier(route: ActivatedRouteSnapshot) {
    // Build the complete path from the root to the input route
    const segments: UrlSegment[][] = route.pathFromRoot.map(r => r.url);
    const subpaths = ([] as UrlSegment[]).concat(...segments).map(segment => segment.path);
    // Result: ${route_depth}-${path}
    return segments.length + '-' + subpaths.join('/');
  }

  private compareObjects(base: any, compare: any): boolean {

    // loop through all properties
    for (const baseProperty in { ...base, ...compare }) {

      // determine if comparrison object has that property, if not: return false
      if (compare.hasOwnProperty(baseProperty)) {
        switch (typeof base[baseProperty]) {
          // if one is object and other is not: return false
          // if they are both objects, recursively call this comparison function
          case 'object':
            if (typeof compare[baseProperty] !== 'object' || !this.compareObjects(base[baseProperty], compare[baseProperty])) {
              return false;
            }
            break;
          // if one is function and other is not: return false
          // if both are functions, compare function.toString() results
          case 'function':
            if (typeof compare[baseProperty] !== 'function' || base[baseProperty].toString() !== compare[baseProperty].toString()) {
              return false;
            }
            break;
          // otherwise, see if they are equal using coercive comparison
          default:
            // tslint:disable-next-line triple-equals
            if (base[baseProperty] != compare[baseProperty]) {
              return false;
            }
        }
      } else {
        return false;
      }
    }

    // returns true only after false HAS NOT BEEN returned through all loops
    return true;
  }
}

如果您有生成唯一键的最佳方法,请评论我的答案,我会更新代码。

感谢所有分享他们解决方案的人。

所有提到的解决方案在我们的案例中都不够充分。我们有较小的商业应用程序:

  1. 简介页
  2. 登录页面
  3. 应用程序(登录后)

我们的要求:

  1. 延迟加载模块
  2. 多级路线
  3. 将所有路由器/组件状态存储在应用程序部分的内存中
  4. 在特定路由上使用默认 angular 重用策略的选项
  5. 注销时销毁存储在内存中的所有组件

我们路线的简化示例:

const routes: Routes = [{
    path: '',
    children: [
        {
            path: '',
            canActivate: [CanActivate],
            loadChildren: () => import('./modules/dashboard/dashboard.module').then(module => module.DashboardModule)
        },
        {
            path: 'companies',
            canActivate: [CanActivate],
            loadChildren: () => import('./modules/company/company.module').then(module => module.CompanyModule)
        }
    ]
},
{
    path: 'login',
    loadChildren: () => import('./modules/login/login.module').then(module => module.LoginModule),
    data: {
        defaultReuseStrategy: true, // Ignore our custom route strategy
        resetReuseStrategy: true // Logout redirect user to login and all data are destroyed
    }
}];

重用策略:

export class AppReuseStrategy implements RouteReuseStrategy {

private handles: Map<string, DetachedRouteHandle> = new Map();

// Asks if a snapshot from the current routing can be used for the future routing.
public shouldReuseRoute(future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean {
    return future.routeConfig === curr.routeConfig;
}

// Asks if a snapshot for the current route already has been stored.
// Return true, if handles map contains the right snapshot and the router should re-attach this snapshot to the routing.
public shouldAttach(route: ActivatedRouteSnapshot): boolean {
    if (this.shouldResetReuseStrategy(route)) {
        this.deactivateAllHandles();
        return false;
    }

    if (this.shouldIgnoreReuseStrategy(route)) {
        return false;
    }

    return this.handles.has(this.getKey(route));
}

// Load the snapshot from storage. It's only called, if the shouldAttach-method returned true.
public retrieve(route: ActivatedRouteSnapshot): DetachedRouteHandle | null {
    return this.handles.get(this.getKey(route)) || null;
}

// Asks if the snapshot should be detached from the router.
// That means that the router will no longer handle this snapshot after it has been stored by calling the store-method.
public shouldDetach(route: ActivatedRouteSnapshot): boolean {
    return !this.shouldIgnoreReuseStrategy(route);
}

// After the router has asked by using the shouldDetach-method and it returned true, the store-method is called (not immediately but some time later).
public store(route: ActivatedRouteSnapshot, handle: DetachedRouteHandle | null): void {
    if (!handle) {
        return;
    }

    this.handles.set(this.getKey(route), handle);
}

private shouldResetReuseStrategy(route: ActivatedRouteSnapshot): boolean {
    let snapshot: ActivatedRouteSnapshot = route;

    while (snapshot.children && snapshot.children.length) {
        snapshot = snapshot.children[0];
    }

    return snapshot.data && snapshot.data.resetReuseStrategy;
}

private shouldIgnoreReuseStrategy(route: ActivatedRouteSnapshot): boolean {
    return route.data && route.data.defaultReuseStrategy;
}

private deactivateAllHandles(): void {
    this.handles.forEach((handle: DetachedRouteHandle) => this.destroyComponent(handle));
    this.handles.clear();
}

private destroyComponent(handle: DetachedRouteHandle): void {
    const componentRef: ComponentRef<any> = handle['componentRef'];

    if (componentRef) {
        componentRef.destroy();
    }
}

private getKey(route: ActivatedRouteSnapshot): string {
    return route.pathFromRoot
        .map((snapshot: ActivatedRouteSnapshot) => snapshot.routeConfig ? snapshot.routeConfig.path : '')
        .filter((path: string) => path.length > 0)
        .join('');
    }
}

我在实施自定义路由重用策略时遇到了这些问题:

  1. 对路由执行操作attach/dettach:管理订阅、清理等;
  2. 仅保留最后一个参数化路由的状态:内存优化;
  3. 重用组件,而不是状态:使用状态管理工具管理状态。
  4. "Cannot reattach ActivatedRouteSnapshot created from a different route"错误;

所以我写了一个库来解决这些问题。该库为 attach/detach 钩子提供服务和装饰器,并使用路由的组件来存储分离的路由,而不是路由的路径。

示例:

/* Usage with decorators */
@onAttach()
public onAttach(): void {
  // your code...
}

@onDetach()
public onDetach(): void {
  // your code...
}

/* Usage with a service */
public ngOnInit(): void {
  this.cacheRouteReuse
    .onAttach(HomeComponent) // or any route's component
    .subscribe(component => {
      // your code...
    });

  this.cacheRouteReuse
    .onDetach(HomeComponent) // or any route's component
    .subscribe(component => {
      // your code...
    });
}

图书馆:https://www.npmjs.com/package/ng-cache-route-reuse

以上所有答案都很好,但是 none 如果您有延迟加载路由器和嵌套路由器,它们中的 none 将正常工作。

为了克服这个问题,shouldReuseRoute 需要更改比较路由的路径:

Path A: abc/xyx/3
Path B: abc/rty/8

<abc>
 <router-outlet></router-outlet>
</abc>

/* If we move from pathA to pathB or vice versa, 
 * then  `routeConfig` will be same since we are routing within the same abc, 
 * but to store the handle properly, you should store fullPath as key.
*/

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


  private getPathFromRoot(route: ActivatedRouteSnapshot) {
    return (route["_urlSegment"]["segments"] as UrlSegment[])
      .map((seg) => seg.path)
      .join("/");
  }

ANGULAR 13(2022 年 2 月 28 日版本)

阅读了大量指南和建议后。我可以解释一下:

首先,你必须明白什么是future和curr。

例如:当您从 localhost/a 导航到 localhost/b,现在您在 b.

案例 1:您想从 /a -> /b

  • shouldReuseRoute: false 因为 future !== current.
  • shouldDetach: true 因为我们将来会保存 (detach) 任何东西到 store 并等待重用 (attach).
  • shouldRetrieve: true || fase 检查 handler 如果是我们 attach 保存的未来组件重用。如果没有,我们什么都不做。 (在本例中为否)

情况 2:您想从 /b?id=1 -> /b?id=2

  • shouldReuseRoute: true 因为 future === current;
  • 应该分离:跳过
  • 应该检索:跳过

情况 3:您想从 /b -> /a

返回
  • shouldReuseRoute: false 因为 future !== current.
  • shouldDetach: true 因为我们将来会保存 (detach) 任何东西到 store 并等待重用 (attach).
  • shouldRetrieve: true || fase 检查 handler 如果是我们 attach 保存的未来组件重用。如果没有,我们什么都不做。 (在这种情况下是)

好的。来自

的更简单的视觉效果
navigate to a
shouldReuseRoute->return true->do nothing

a->b
shouldReuseRoute()->return false->shouldDetach()->return true->store a

then b->a
shouldReuseRoute()->return false->shouldDetach()->return true->store b->retrieve() return a ->attach() a.

然后从

最后来自 angular 团队的正确代码:https://github.com/angular/angular/issues/44383

export class CustomRouteReuseStrategy implements RouteReuseStrategy { 
    private handlers: Map<Route, DetachedRouteHandle> = new Map();

    constructor() {}

    public shouldDetach(_route: ActivatedRouteSnapshot): boolean {
        return true;
    }

    public store(
        route: ActivatedRouteSnapshot,
        handle: DetachedRouteHandle
    ): void {
        if (!route.routeConfig) return;
        this.handlers.set(route.routeConfig, handle);
    }

    public shouldAttach(route: ActivatedRouteSnapshot): boolean {
        return !!route.routeConfig && !!this.handlers.get(route.routeConfig);
    }

    public retrieve(route: ActivatedRouteSnapshot): DetachedRouteHandle|null {
        if (!route.routeConfig || !this.handlers.has(route.routeConfig)) return null;
        return this.handlers.get(route.routeConfig)!;
    }

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