angularangular-router

How can I add custom data to an Angular route?


I am declaring my routes typically like this:

{
   path: 'datasel/:datasel',
   component: aComponent,
   resolve: { model: AWATranslationLoaderResolver },
   data: { resolvedata: 'Assets', reuse: true },
}

Is it possible to add some writable data to a route? My idea is to modify that data in aComponent so the reuse strategy would know about some important events happening in the component.

Something like this would be nice to have in component:

    this.router.events.subscribe(ev => {
        if (ev instanceof ActivationEnd &&
            Object.is(ev?.snapshot?.component, aComponent)) {
            ev.snapshot.customData.inportantEvent = true;
        }
    });

and then read that data in the custom reuse class:

shouldAttach(route: ActivatedRouteSnapshot): boolean {
    console.log(route.customData.importantEvent);
    return !!this.handlers[this.getUrl(route)];
}

Solution

  • If you would like to pass some complex data, you probably need to use a service for this purpose.

    As a quick and universal solution, you can write a service which is provided in root, with set and get methods. The set method will set any data to store, so previous page can set a payload. the get method will return the data (if it was set on previous page) and after returning set null to the store. So the next page can get data once. Any next attempt to get data will return null. It will help you to pass any data between pages, during the app routing.

    Example of a basic implementation of the service:

    import {Injectable} from "@angular/core";
    
    @Injectable({providedIn: "root"})
    export class RoutePayloadService {
      private _store: any = null;
    
      set(data: any) {
        this._store = data
      }
    
      get<T>(): T {
        const buff = this._store;
        this._store = null;
        return buff as T;
      }
    }