From ea2e75d910b59adae4117d2e25d56ffee7b716ab Mon Sep 17 00:00:00 2001 From: griest024 Date: Wed, 4 Dec 2024 18:08:41 -0500 Subject: [PATCH] fix(router): old route data is replayed for new routes (#3352) --- .../src/activated-route/service.spec.ts | 23 +++++++++++++++++++ libs/router/src/activated-route/service.ts | 4 ++-- 2 files changed, 25 insertions(+), 2 deletions(-) diff --git a/libs/router/src/activated-route/service.spec.ts b/libs/router/src/activated-route/service.spec.ts index b8f5c55806..45e4225461 100644 --- a/libs/router/src/activated-route/service.spec.ts +++ b/libs/router/src/activated-route/service.spec.ts @@ -4,6 +4,7 @@ import { provideRouter, Router, } from '@angular/router'; +import { tap } from 'rxjs'; import { DaffRouterActivatedRoute } from './service'; @@ -36,6 +37,13 @@ describe('@daffodil/router | DaffRouterActivatedRoute', () => { }, ], }, + { + path: 'other', + data: { + test: 'other', + }, + component: TestComponent, + }, ], }, ]), @@ -58,4 +66,19 @@ describe('@daffodil/router | DaffRouterActivatedRoute', () => { }); router.initialNavigation(); }); + + it('should only emit the last value when the stream is subscribed to late', async (done) => { + const spy = jasmine.createSpy(); + service.route$.subscribe(); + router.initialNavigation(); + await router.navigateByUrl('/'); + await router.navigateByUrl('/other'); + service.route$.pipe( + tap(spy), + ).subscribe((route) => { + expect(spy).toHaveBeenCalledTimes(1); + expect(route.snapshot.data['test']).toEqual('other'); + done(); + }); + }); }); diff --git a/libs/router/src/activated-route/service.ts b/libs/router/src/activated-route/service.ts index 08c09e233f..7a24c001c8 100644 --- a/libs/router/src/activated-route/service.ts +++ b/libs/router/src/activated-route/service.ts @@ -26,7 +26,7 @@ const getActivatedRoute = (routerState: RouterState): ActivatedRoute => { * * Note that this service operates by listening to router events. It is therefore recommended to * inject this service in the root and subscribe to `route$` on app init so that all routing events are captured. - * The consumer can then subscribe at any later time (after all navigations) and the emission stream will be replayed. + * The consumer can then subscribe at any later time (after all navigations) and the last emitted value will be replayed. * {@link provideDaffRouterActivatedRoute} is the recommended way to do this. */ @Injectable({ @@ -36,7 +36,7 @@ export class DaffRouterActivatedRoute { route$: Observable = this.router.events.pipe( filter((event) => event instanceof NavigationEnd), map(() => getActivatedRoute(this.router.routerState)), - shareReplay(), + shareReplay(1), ); constructor(