Skip to content

Commit

Permalink
fix(router): old route data is replayed for new routes (#3352)
Browse files Browse the repository at this point in the history
  • Loading branch information
griest024 authored Dec 4, 2024
1 parent d3e9f33 commit ea2e75d
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 2 deletions.
23 changes: 23 additions & 0 deletions libs/router/src/activated-route/service.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import {
provideRouter,
Router,
} from '@angular/router';
import { tap } from 'rxjs';

import { DaffRouterActivatedRoute } from './service';

Expand Down Expand Up @@ -36,6 +37,13 @@ describe('@daffodil/router | DaffRouterActivatedRoute', () => {
},
],
},
{
path: 'other',
data: {
test: 'other',
},
component: TestComponent,
},
],
},
]),
Expand All @@ -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();
});
});
});
4 changes: 2 additions & 2 deletions libs/router/src/activated-route/service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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({
Expand All @@ -36,7 +36,7 @@ export class DaffRouterActivatedRoute {
route$: Observable<ActivatedRoute> = this.router.events.pipe(
filter((event) => event instanceof NavigationEnd),
map(() => getActivatedRoute(this.router.routerState)),
shareReplay(),
shareReplay(1),
);

constructor(
Expand Down

0 comments on commit ea2e75d

Please sign in to comment.