Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error: Cannot reattach ActivatedRouteSnapshot created from a different route

I am trying to implement the RouteReuseStrategy class. It works fine when I navigate to top level paths.

As soon as a path has child paths and I navigate to the child path, then navigate back to a top level path I receive the following error:

Error: Uncaught (in promise): Error: Cannot reattach ActivatedRouteSnapshot created from a different route

I have created a plunker to demonstrate the error. I see the plunker does not work in IE 11, please view it in the latest version of Chrome

Steps to reproduce the error:

Step1: enter image description here

Step2 enter image description here

Step3 enter image description here

Step4 enter image description here

You can view the error in the console: enter image description here

I have tried the implementation found on this article

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;
    }

}

And the implementation of this stackoverflow answer

/**
 * 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 (===)
     * @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;
    }
}

Is RouteReuseStrategy ready for child paths? Or is there another way to get RouteReuseStrategy working with paths that contain child paths

like image 989
Tjaart van der Walt Avatar asked Jan 11 '17 07:01

Tjaart van der Walt


People also ask

What is the difference between ActivatedRoute and ActivatedRouteSnapshot?

Since ActivatedRoute can be reused, ActivatedRouteSnapshot is an immutable object representing a particular version of ActivatedRoute . It exposes all the same properties as ActivatedRoute as plain values, while ActivatedRoute exposes them as observables.

What is the use of ActivatedRouteSnapshot?

ActivatedRouteSnapshotlinkContains the information about a route associated with a component loaded in an outlet at a particular moment in time. ActivatedRouteSnapshot can also be used to traverse the router state tree.

What is RouteReuseStrategy?

RouteReuseStrategy : In simple sentence it caches the components and prevent it from reload the components again and again. While in angular to navigate from one page to another page, we have an concept called Routing. By using this we can redirect from one page to another.

Can you explain the difference between ActivatedRoute and RouterState?

Difference between activatedroute and routerstateActivatedRoute interface provides access to information about a route associated with a component that is loaded in an outlet. Use to traverse the RouterState tree and extract information from nodes.


4 Answers

I added a workaround to never retrieve detached routes when on a route with loadChildren by modifying my retrieve function in the custom RouteReuseStrategy.

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

I'm not sure it is a perfect solution for all scenarios but in my case it works.

like image 123
IveMadeAHugeMistake Avatar answered Nov 07 '22 02:11

IveMadeAHugeMistake


Angular router is unnecessarily complex and custom strategies continue this trend.

Your custom strategy uses route.routerConfig.path as a key for stored routes.

It stores (overwrites) two different routes for the same path person/:id:

  1. /person/%23123456789%23/edit
  2. /person/%23123456789%23/view

First time view route was stored, second time edit, when you open view again last stored route is edit, but view is expected.

This routes are not compatible according to router opinion, it checks nodes recursively and finds out that routerConfig for ViewPersonComponent is not the same as routerConfig for EditPersonComponent, boom!

So either routerConfig.path must not be used as a key or it is router design problem/limitation.

like image 36
kemsky Avatar answered Nov 07 '22 03:11

kemsky


Here is a way to generate unique keys for routes in the strategy class. I had similar problem but once i started generating unique keys the problem disappeared:

private takeFullUrl(route: ActivatedRouteSnapshot) {
  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;
  }
  const segments = [];
  // Then build a unique key-path by going to the root.
  while (next) {
    segments.push(next.url.join('/'));
    next = next.parent;
  }
  return compact(segments.reverse()).join('/');
}

More on that https://github.com/angular/angular/issues/13869#issuecomment-344403045

like image 2
barbatus Avatar answered Nov 07 '22 03:11

barbatus


I ran into a similar problem and modifying my unique key method solved it.

private routeToUrl(route: ActivatedRouteSnapshot): string {
    if (route.url) {
        if (route.url.length) {
            return route.url.join('/');
        } else {
            if (typeof route.component === 'function') {
                return `[${route.component.name}]`;
            } else if (typeof route.component === 'string') {
                return `[${route.component}]`;
            } else {
                return `[null]`;
            }
        }
    } else {
        return '(null)';
    }
}


private getChildRouteKeys(route:ActivatedRouteSnapshot): string {
    let  url = this.routeToUrl(route);
    return route.children.reduce((fin, cr) => fin += this.getChildRouteKeys(cr), url);
}

private getRouteKey(route: ActivatedRouteSnapshot) {
    let url = route.pathFromRoot.map(it => this.routeToUrl(it)).join('/') + '*';
    url += route.children.map(cr => this.getChildRouteKeys(cr));
    return url;
}

Previously I only built off the first child, now I just recursively build my key off all children. I did not write the routeToUrl function, I got it from an article I read on custom reuse strategies a while back and it is unmodified.

like image 2
bryan60 Avatar answered Nov 07 '22 02:11

bryan60