RouteReuseStrategy 如何只在用户返回(历史)时实现?

How to implement RouteReuseStrategy only when user goes back (history)?

我有一个 Angular 2 项目,我在其中实施了一个自定义重用策略,该策略存储分离的路由并在它们已经存在的情况下重用它们。

很好,但我只想在用户单击导航器返回按钮时使用此机制,而不是在用户直接单击我的页面或菜单中的某些 link 时使用此机制。

目的是,如果用户是通过“返回”按钮来的,则在他离开后会显示路线,但如果用户单击 link 或菜单,将重新加载页面并从服务器获取数据将再次获取!

我试图查看 ActivatedRouteSnapshot 中是否存在用户来自历史记录而不是直接来自 link(使用 router.navigate)的信息,但我不能'什么都看不到。

有没有办法实现我想要的?

您可以检测后退按钮是否按下:

constructor(location: LocationStrategy) {
  location.onPopState(() => {
    console.log('Back button pressed!');
    console.log(window.location);
  });
}

您应该添加 @Injectable() 以注入 LocationStrategy

如果有人想知道如何确切地实现这一点,这里有一些更详细的代码。

如@youri 所写,您在 route-custom-strategy.ts 中添加以下代码:

@Injectable()

export class CustomRouteReuseStategy implements RouteReuseStrategy {

    constructor(location: LocationStrategy) {
        location.onPopState(() => {
            this.back = true
            console.log('Back button pressed!', this.back);
        });
    }

    // Back-navigation monitoring
    back: boolean = false

   // ------------ Your RouteReuseStrategy code ---------------
}

记得加上Injectable().

既然您已将 back 变量设置为用户向后导航(或向前导航 - 请记住 onPopState() 会触发所有弹出状态)的标志,我们需要确保shouldAttach 仅在向后(或向前)导航时触发。

我假设您的 shouldAttach 代码看起来像这样:

shouldAttach(route: ActivatedRouteSnapshot): boolean {

    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);
   
    return paramsMatch && queryParamsMatch;
}

因此您只需添加一个参数来检查我们的 this.back 布尔值和一行代码以将该值重置为 false 以便捕捉下一个返回导航。 上面的代码变成:

shouldAttach(route: ActivatedRouteSnapshot): boolean {

    const storedObject = this.storedRoutes[id];
    const canAttach = !!route.routeConfig && !!storedObject;

    if (!canAttach || !this.back)  {
       this.back = false
       return false;
    }

    this.back = false
    const paramsMatch = this.compareObjects(route.params, storedObject.snapshot.params);
    const queryParamsMatch = this.compareObjects(route.queryParams, storedObject.snapshot.queryParams);
   
    return paramsMatch && queryParamsMatch;
}

就是这样。现在,您将只会在 back/forward 导航上重复使用存储的页面,并且当您通过单击路线导航时将加载一个新组件。