/
router.ts
1623 lines (1507 loc) Β· 66.9 KB
/
router.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {Location, PopStateEvent} from '@angular/common';
import {Compiler, Injectable, Injector, NgModuleFactoryLoader, NgModuleRef, NgZone, Type, Ι΅Console as Console} from '@angular/core';
import {BehaviorSubject, EMPTY, Observable, of, Subject, SubscriptionLike} from 'rxjs';
import {catchError, filter, finalize, map, switchMap, tap} from 'rxjs/operators';
import {QueryParamsHandling, Route, Routes} from './config';
import {createRouterState} from './create_router_state';
import {createUrlTree} from './create_url_tree';
import {Event, GuardsCheckEnd, GuardsCheckStart, NavigationCancel, NavigationEnd, NavigationError, NavigationStart, NavigationTrigger, ResolveEnd, ResolveStart, RouteConfigLoadEnd, RouteConfigLoadStart, RoutesRecognized} from './events';
import {activateRoutes} from './operators/activate_routes';
import {applyRedirects} from './operators/apply_redirects';
import {checkGuards} from './operators/check_guards';
import {recognize} from './operators/recognize';
import {resolveData} from './operators/resolve_data';
import {switchTap} from './operators/switch_tap';
import {DefaultRouteReuseStrategy, RouteReuseStrategy} from './route_reuse_strategy';
import {RouterConfigLoader} from './router_config_loader';
import {ChildrenOutletContexts} from './router_outlet_context';
import {ActivatedRoute, createEmptyState, RouterState, RouterStateSnapshot} from './router_state';
import {isNavigationCancelingError, navigationCancelingError, Params} from './shared';
import {DefaultUrlHandlingStrategy, UrlHandlingStrategy} from './url_handling_strategy';
import {containsTree, createEmptyUrlTree, IsActiveMatchOptions, UrlSerializer, UrlTree} from './url_tree';
import {standardizeConfig, validateConfig} from './utils/config';
import {Checks, getAllRouteGuards} from './utils/preactivation';
import {isUrlTree} from './utils/type_guards';
/**
* @description
*
* Options that modify the `Router` URL.
* Supply an object containing any of these properties to a `Router` navigation function to
* control how the target URL should be constructed.
*
* @see [Router.navigate() method](api/router/Router#navigate)
* @see [Router.createUrlTree() method](api/router/Router#createurltree)
* @see [Routing and Navigation guide](guide/router)
*
* @publicApi
*/
export interface UrlCreationOptions {
/**
* Specifies a root URI to use for relative navigation.
*
* For example, consider the following route configuration where the parent route
* has two children.
*
* ```
* [{
* path: 'parent',
* component: ParentComponent,
* children: [{
* path: 'list',
* component: ListComponent
* },{
* path: 'child',
* component: ChildComponent
* }]
* }]
* ```
*
* The following `go()` function navigates to the `list` route by
* interpreting the destination URI as relative to the activated `child` route
*
* ```
* @Component({...})
* class ChildComponent {
* constructor(private router: Router, private route: ActivatedRoute) {}
*
* go() {
* this.router.navigate(['../list'], { relativeTo: this.route });
* }
* }
* ```
*
* A value of `null` or `undefined` indicates that the navigation commands should be applied
* relative to the root.
*/
relativeTo?: ActivatedRoute|null;
/**
* Sets query parameters to the URL.
*
* ```
* // Navigate to /results?page=1
* this.router.navigate(['/results'], { queryParams: { page: 1 } });
* ```
*/
queryParams?: Params|null;
/**
* Sets the hash fragment for the URL.
*
* ```
* // Navigate to /results#top
* this.router.navigate(['/results'], { fragment: 'top' });
* ```
*/
fragment?: string;
/**
* How to handle query parameters in the router link for the next navigation.
* One of:
* * `preserve` : Preserve current parameters.
* * `merge` : Merge new with current parameters.
*
* The "preserve" option discards any new query params:
* ```
* // from /view1?page=1 to/view2?page=1
* this.router.navigate(['/view2'], { queryParams: { page: 2 }, queryParamsHandling: "preserve"
* });
* ```
* The "merge" option appends new query params to the params from the current URL:
* ```
* // from /view1?page=1 to/view2?page=1&otherKey=2
* this.router.navigate(['/view2'], { queryParams: { otherKey: 2 }, queryParamsHandling: "merge"
* });
* ```
* In case of a key collision between current parameters and those in the `queryParams` object,
* the new value is used.
*
*/
queryParamsHandling?: QueryParamsHandling|null;
/**
* When true, preserves the URL fragment for the next navigation
*
* ```
* // Preserve fragment from /results#top to /view#top
* this.router.navigate(['/view'], { preserveFragment: true });
* ```
*/
preserveFragment?: boolean;
}
/**
* @description
*
* Options that modify the `Router` navigation strategy.
* Supply an object containing any of these properties to a `Router` navigation function to
* control how the navigation should be handled.
*
* @see [Router.navigate() method](api/router/Router#navigate)
* @see [Router.navigateByUrl() method](api/router/Router#navigatebyurl)
* @see [Routing and Navigation guide](guide/router)
*
* @publicApi
*/
export interface NavigationBehaviorOptions {
/**
* When true, navigates without pushing a new state into history.
*
* ```
* // Navigate silently to /view
* this.router.navigate(['/view'], { skipLocationChange: true });
* ```
*/
skipLocationChange?: boolean;
/**
* When true, navigates while replacing the current state in history.
*
* ```
* // Navigate to /view
* this.router.navigate(['/view'], { replaceUrl: true });
* ```
*/
replaceUrl?: boolean;
/**
* Developer-defined state that can be passed to any navigation.
* Access this value through the `Navigation.extras` object
* returned from the [Router.getCurrentNavigation()
* method](api/router/Router#getcurrentnavigation) while a navigation is executing.
*
* After a navigation completes, the router writes an object containing this
* value together with a `navigationId` to `history.state`.
* The value is written when `location.go()` or `location.replaceState()`
* is called before activating this route.
*
* Note that `history.state` does not pass an object equality test because
* the router adds the `navigationId` on each navigation.
*
*/
state?: {[k: string]: any};
}
/**
* @description
*
* Options that modify the `Router` navigation strategy.
* Supply an object containing any of these properties to a `Router` navigation function to
* control how the target URL should be constructed or interpreted.
*
* @see [Router.navigate() method](api/router/Router#navigate)
* @see [Router.navigateByUrl() method](api/router/Router#navigatebyurl)
* @see [Router.createUrlTree() method](api/router/Router#createurltree)
* @see [Routing and Navigation guide](guide/router)
* @see UrlCreationOptions
* @see NavigationBehaviorOptions
*
* @publicApi
*/
export interface NavigationExtras extends UrlCreationOptions, NavigationBehaviorOptions {}
/**
* Error handler that is invoked when a navigation error occurs.
*
* If the handler returns a value, the navigation Promise is resolved with this value.
* If the handler throws an exception, the navigation Promise is rejected with
* the exception.
*
* @publicApi
*/
export type ErrorHandler = (error: any) => any;
function defaultErrorHandler(error: any): any {
throw error;
}
function defaultMalformedUriErrorHandler(
error: URIError, urlSerializer: UrlSerializer, url: string): UrlTree {
return urlSerializer.parse('/');
}
export type RestoredState = {
[k: string]: any,
// TODO(#27607): Remove `navigationId` and `Ι΅routerPageId` and move to `ng` or `Ι΅` namespace.
navigationId: number,
// The `Ι΅` prefix is there to reduce the chance of colliding with any existing user properties on
// the history state.
Ι΅routerPageId?: number,
};
/**
* Information about a navigation operation.
* Retrieve the most recent navigation object with the
* [Router.getCurrentNavigation() method](api/router/Router#getcurrentnavigation) .
*
* * *id* : The unique identifier of the current navigation.
* * *initialUrl* : The target URL passed into the `Router#navigateByUrl()` call before navigation.
* This is the value before the router has parsed or applied redirects to it.
* * *extractedUrl* : The initial target URL after being parsed with `UrlSerializer.extract()`.
* * *finalUrl* : The extracted URL after redirects have been applied.
* This URL may not be available immediately, therefore this property can be `undefined`.
* It is guaranteed to be set after the `RoutesRecognized` event fires.
* * *trigger* : Identifies how this navigation was triggered.
* -- 'imperative'--Triggered by `router.navigateByUrl` or `router.navigate`.
* -- 'popstate'--Triggered by a popstate event.
* -- 'hashchange'--Triggered by a hashchange event.
* * *extras* : A `NavigationExtras` options object that controlled the strategy used for this
* navigation.
* * *previousNavigation* : The previously successful `Navigation` object. Only one previous
* navigation is available, therefore this previous `Navigation` object has a `null` value for its
* own `previousNavigation`.
*
* @publicApi
*/
export interface Navigation {
/**
* The unique identifier of the current navigation.
*/
id: number;
/**
* The target URL passed into the `Router#navigateByUrl()` call before navigation. This is
* the value before the router has parsed or applied redirects to it.
*/
initialUrl: string|UrlTree;
/**
* The initial target URL after being parsed with `UrlSerializer.extract()`.
*/
extractedUrl: UrlTree;
/**
* The extracted URL after redirects have been applied.
* This URL may not be available immediately, therefore this property can be `undefined`.
* It is guaranteed to be set after the `RoutesRecognized` event fires.
*/
finalUrl?: UrlTree;
/**
* Identifies how this navigation was triggered.
*
* * 'imperative'--Triggered by `router.navigateByUrl` or `router.navigate`.
* * 'popstate'--Triggered by a popstate event.
* * 'hashchange'--Triggered by a hashchange event.
*/
trigger: 'imperative'|'popstate'|'hashchange';
/**
* Options that controlled the strategy used for this navigation.
* See `NavigationExtras`.
*/
extras: NavigationExtras;
/**
* The previously successful `Navigation` object. Only one previous navigation
* is available, therefore this previous `Navigation` object has a `null` value
* for its own `previousNavigation`.
*/
previousNavigation: Navigation|null;
}
export type NavigationTransition = {
id: number,
targetPageId: number,
currentUrlTree: UrlTree,
currentRawUrl: UrlTree,
extractedUrl: UrlTree,
urlAfterRedirects: UrlTree,
rawUrl: UrlTree,
extras: NavigationExtras,
resolve: any,
reject: any,
promise: Promise<boolean>,
source: NavigationTrigger,
restoredState: RestoredState|null,
currentSnapshot: RouterStateSnapshot,
targetSnapshot: RouterStateSnapshot|null,
currentRouterState: RouterState,
targetRouterState: RouterState|null,
guards: Checks,
guardsResult: boolean|UrlTree|null,
};
/**
* @internal
*/
export type RouterHook = (snapshot: RouterStateSnapshot, runExtras: {
appliedUrlTree: UrlTree,
rawUrlTree: UrlTree,
skipLocationChange: boolean,
replaceUrl: boolean,
navigationId: number
}) => Observable<void>;
/**
* @internal
*/
function defaultRouterHook(snapshot: RouterStateSnapshot, runExtras: {
appliedUrlTree: UrlTree,
rawUrlTree: UrlTree,
skipLocationChange: boolean,
replaceUrl: boolean,
navigationId: number
}): Observable<void> {
return of(null) as any;
}
/**
* Information related to a location change, necessary for scheduling follow-up Router navigations.
*/
type LocationChangeInfo = {
source: 'popstate'|'hashchange',
urlTree: UrlTree,
state: RestoredState|null,
transitionId: number
};
/**
* The equivalent `IsActiveMatchOptions` options for `Router.isActive` is called with `true`
* (exact = true).
*/
export const exactMatchOptions: IsActiveMatchOptions = {
paths: 'exact',
fragment: 'ignored',
matrixParams: 'ignored',
queryParams: 'exact'
};
/**
* The equivalent `IsActiveMatchOptions` options for `Router.isActive` is called with `false`
* (exact = false).
*/
export const subsetMatchOptions: IsActiveMatchOptions = {
paths: 'subset',
fragment: 'ignored',
matrixParams: 'ignored',
queryParams: 'subset'
};
/**
* @description
*
* A service that provides navigation among views and URL manipulation capabilities.
*
* @see `Route`.
* @see [Routing and Navigation Guide](guide/router).
*
* @ngModule RouterModule
*
* @publicApi
*/
@Injectable()
export class Router {
/**
* Represents the activated `UrlTree` that the `Router` is configured to handle (through
* `UrlHandlingStrategy`). That is, after we find the route config tree that we're going to
* activate, run guards, and are just about to activate the route, we set the currentUrlTree.
*
* This should match the `browserUrlTree` when a navigation succeeds. If the
* `UrlHandlingStrategy.shouldProcessUrl` is `false`, only the `browserUrlTree` is updated.
*/
private currentUrlTree: UrlTree;
/**
* Meant to represent the entire browser url after a successful navigation. In the life of a
* navigation transition:
* 1. The rawUrl represents the full URL that's being navigated to
* 2. We apply redirects, which might only apply to _part_ of the URL (due to
* `UrlHandlingStrategy`).
* 3. Right before activation (because we assume activation will succeed), we update the
* rawUrlTree to be a combination of the urlAfterRedirects (again, this might only apply to part
* of the initial url) and the rawUrl of the transition (which was the original navigation url in
* its full form).
*/
private rawUrlTree: UrlTree;
/**
* Meant to represent the part of the browser url that the `Router` is set up to handle (via the
* `UrlHandlingStrategy`). This value is updated immediately after the browser url is updated (or
* the browser url update is skipped via `skipLocationChange`). With that, note that
* `browserUrlTree` _may not_ reflect the actual browser URL for two reasons:
*
* 1. `UrlHandlingStrategy` only handles part of the URL
* 2. `skipLocationChange` does not update the browser url.
*
* So to reiterate, `browserUrlTree` only represents the Router's internal understanding of the
* current route, either before guards with `urlUpdateStrategy === 'eager'` or right before
* activation with `'deferred'`.
*
* This should match the `currentUrlTree` when the navigation succeeds.
*/
private browserUrlTree: UrlTree;
private readonly transitions: BehaviorSubject<NavigationTransition>;
private navigations: Observable<NavigationTransition>;
private lastSuccessfulNavigation: Navigation|null = null;
private currentNavigation: Navigation|null = null;
private disposed = false;
private locationSubscription?: SubscriptionLike;
/**
* Tracks the previously seen location change from the location subscription so we can compare
* the two latest to see if they are duplicates. See setUpLocationChangeListener.
*/
private lastLocationChangeInfo: LocationChangeInfo|null = null;
private navigationId: number = 0;
/**
* The id of the currently active page in the router.
* Updated to the transition's target id on a successful navigation.
*
* This is used to track what page the router last activated. When an attempted navigation fails,
* the router can then use this to compute how to restore the state back to the previously active
* page.
*/
private currentPageId: number = 0;
/**
* The Ι΅routerPageId of whatever page is currently active in the browser history. This is
* important for computing the target page id for new navigations because we need to ensure each
* page id in the browser history is 1 more than the previous entry.
*/
private get browserPageId(): number|undefined {
return (this.location.getState() as RestoredState | null)?.Ι΅routerPageId;
}
private configLoader: RouterConfigLoader;
private ngModule: NgModuleRef<any>;
private console: Console;
private isNgZoneEnabled: boolean = false;
/**
* An event stream for routing events in this NgModule.
*/
public readonly events: Observable<Event> = new Subject<Event>();
/**
* The current state of routing in this NgModule.
*/
public readonly routerState: RouterState;
/**
* A handler for navigation errors in this NgModule.
*/
errorHandler: ErrorHandler = defaultErrorHandler;
/**
* A handler for errors thrown by `Router.parseUrl(url)`
* when `url` contains an invalid character.
* The most common case is a `%` sign
* that's not encoded and is not part of a percent encoded sequence.
*/
malformedUriErrorHandler:
(error: URIError, urlSerializer: UrlSerializer,
url: string) => UrlTree = defaultMalformedUriErrorHandler;
/**
* True if at least one navigation event has occurred,
* false otherwise.
*/
navigated: boolean = false;
private lastSuccessfulId: number = -1;
/**
* Hooks that enable you to pause navigation,
* either before or after the preactivation phase.
* Used by `RouterModule`.
*
* @internal
*/
hooks: {
beforePreactivation: RouterHook,
afterPreactivation: RouterHook
} = {beforePreactivation: defaultRouterHook, afterPreactivation: defaultRouterHook};
/**
* A strategy for extracting and merging URLs.
* Used for AngularJS to Angular migrations.
*/
urlHandlingStrategy: UrlHandlingStrategy = new DefaultUrlHandlingStrategy();
/**
* A strategy for re-using routes.
*/
routeReuseStrategy: RouteReuseStrategy = new DefaultRouteReuseStrategy();
/**
* How to handle a navigation request to the current URL. One of:
*
* - `'ignore'` : The router ignores the request.
* - `'reload'` : The router reloads the URL. Use to implement a "refresh" feature.
*
* Note that this only configures whether the Route reprocesses the URL and triggers related
* action and events like redirects, guards, and resolvers. By default, the router re-uses a
* component instance when it re-navigates to the same component type without visiting a different
* component first. This behavior is configured by the `RouteReuseStrategy`. In order to reload
* routed components on same url navigation, you need to set `onSameUrlNavigation` to `'reload'`
* _and_ provide a `RouteReuseStrategy` which returns `false` for `shouldReuseRoute`.
*/
onSameUrlNavigation: 'reload'|'ignore' = 'ignore';
/**
* How to merge parameters, data, and resolved data from parent to child
* routes. One of:
*
* - `'emptyOnly'` : Inherit parent parameters, data, and resolved data
* for path-less or component-less routes.
* - `'always'` : Inherit parent parameters, data, and resolved data
* for all child routes.
*/
paramsInheritanceStrategy: 'emptyOnly'|'always' = 'emptyOnly';
/**
* Determines when the router updates the browser URL.
* By default (`"deferred"`), updates the browser URL after navigation has finished.
* Set to `'eager'` to update the browser URL at the beginning of navigation.
* You can choose to update early so that, if navigation fails,
* you can show an error message with the URL that failed.
*/
urlUpdateStrategy: 'deferred'|'eager' = 'deferred';
/**
* Enables a bug fix that corrects relative link resolution in components with empty paths.
* @see `RouterModule`
*/
relativeLinkResolution: 'legacy'|'corrected' = 'corrected';
/**
* Configures how the Router attempts to restore state when a navigation is cancelled.
*
* 'replace' - Always uses `location.replaceState` to set the browser state to the state of the
* router before the navigation started.
*
* 'computed' - Will always return to the same state that corresponds to the actual Angular route
* when the navigation gets cancelled right after triggering a `popstate` event.
*
* The default value is `replace`
*
* @internal
*/
// TODO(atscott): Determine how/when/if to make this public API
// This shouldnβt be an option at all but may need to be in order to allow migration without a
// breaking change. We need to determine if it should be made into public api (or if we forgo
// the option and release as a breaking change bug fix in a major version).
canceledNavigationResolution: 'replace'|'computed' = 'replace';
/**
* Creates the router service.
*/
// TODO: vsavkin make internal after the final is out.
constructor(
private rootComponentType: Type<any>|null, private urlSerializer: UrlSerializer,
private rootContexts: ChildrenOutletContexts, private location: Location, injector: Injector,
loader: NgModuleFactoryLoader, compiler: Compiler, public config: Routes) {
const onLoadStart = (r: Route) => this.triggerEvent(new RouteConfigLoadStart(r));
const onLoadEnd = (r: Route) => this.triggerEvent(new RouteConfigLoadEnd(r));
this.ngModule = injector.get(NgModuleRef);
this.console = injector.get(Console);
const ngZone = injector.get(NgZone);
this.isNgZoneEnabled = ngZone instanceof NgZone && NgZone.isInAngularZone();
this.resetConfig(config);
this.currentUrlTree = createEmptyUrlTree();
this.rawUrlTree = this.currentUrlTree;
this.browserUrlTree = this.currentUrlTree;
this.configLoader = new RouterConfigLoader(loader, compiler, onLoadStart, onLoadEnd);
this.routerState = createEmptyState(this.currentUrlTree, this.rootComponentType);
this.transitions = new BehaviorSubject<NavigationTransition>({
id: 0,
targetPageId: 0,
currentUrlTree: this.currentUrlTree,
currentRawUrl: this.currentUrlTree,
extractedUrl: this.urlHandlingStrategy.extract(this.currentUrlTree),
urlAfterRedirects: this.urlHandlingStrategy.extract(this.currentUrlTree),
rawUrl: this.currentUrlTree,
extras: {},
resolve: null,
reject: null,
promise: Promise.resolve(true),
source: 'imperative',
restoredState: null,
currentSnapshot: this.routerState.snapshot,
targetSnapshot: null,
currentRouterState: this.routerState,
targetRouterState: null,
guards: {canActivateChecks: [], canDeactivateChecks: []},
guardsResult: null,
});
this.navigations = this.setupNavigations(this.transitions);
this.processNavigations();
}
private setupNavigations(transitions: Observable<NavigationTransition>):
Observable<NavigationTransition> {
const eventsSubject = (this.events as Subject<Event>);
return transitions.pipe(
filter(t => t.id !== 0),
// Extract URL
map(t =>
({...t, extractedUrl: this.urlHandlingStrategy.extract(t.rawUrl)} as
NavigationTransition)),
// Using switchMap so we cancel executing navigations when a new one comes in
switchMap(t => {
let completed = false;
let errored = false;
return of(t).pipe(
// Store the Navigation object
tap(t => {
this.currentNavigation = {
id: t.id,
initialUrl: t.currentRawUrl,
extractedUrl: t.extractedUrl,
trigger: t.source,
extras: t.extras,
previousNavigation: this.lastSuccessfulNavigation ?
{...this.lastSuccessfulNavigation, previousNavigation: null} :
null
};
}),
switchMap(t => {
const browserUrlTree = this.browserUrlTree.toString();
const urlTransition = !this.navigated ||
t.extractedUrl.toString() !== browserUrlTree ||
// Navigations which succeed or ones which fail and are cleaned up
// correctly should result in `browserUrlTree` and `currentUrlTree`
// matching. If this is not the case, assume something went wrong and try
// processing the URL again.
browserUrlTree !== this.currentUrlTree.toString();
const processCurrentUrl =
(this.onSameUrlNavigation === 'reload' ? true : urlTransition) &&
this.urlHandlingStrategy.shouldProcessUrl(t.rawUrl);
// If the source of the navigation is from a browser event, the URL is
// already updated. We already need to sync the internal state.
if (isBrowserTriggeredNavigation(t.source)) {
// TODO(atscott): this should be `t.extractedUrl`. The `browserUrlTree`
// should only be the part of the URL that is handled by the router. In
// addition, this should only be done if we process the current url.
this.browserUrlTree = t.rawUrl;
}
if (processCurrentUrl) {
return of(t).pipe(
// Fire NavigationStart event
switchMap(t => {
const transition = this.transitions.getValue();
eventsSubject.next(new NavigationStart(
t.id, this.serializeUrl(t.extractedUrl), t.source,
t.restoredState));
if (transition !== this.transitions.getValue()) {
return EMPTY;
}
// This delay is required to match old behavior that forced
// navigation to always be async
return Promise.resolve(t);
}),
// ApplyRedirects
applyRedirects(
this.ngModule.injector, this.configLoader, this.urlSerializer,
this.config),
// Update the currentNavigation
tap(t => {
this.currentNavigation = {
...this.currentNavigation!,
finalUrl: t.urlAfterRedirects
};
}),
// Recognize
recognize(
this.rootComponentType, this.config,
(url) => this.serializeUrl(url), this.paramsInheritanceStrategy,
this.relativeLinkResolution),
// Update URL if in `eager` update mode
tap(t => {
if (this.urlUpdateStrategy === 'eager') {
if (!t.extras.skipLocationChange) {
this.setBrowserUrl(t.urlAfterRedirects, t);
// TODO(atscott): The above line is incorrect. It sets the url to
// only the part that is handled by the router. It should merge
// that with the rawUrl so the url includes segments not handled
// by the router:
// const rawUrl = this.urlHandlingStrategy.merge(
// t.urlAfterRedirects, t.rawUrl);
// this.setBrowserUrl(rawUrl, t);
}
this.browserUrlTree = t.urlAfterRedirects;
}
// Fire RoutesRecognized
const routesRecognized = new RoutesRecognized(
t.id, this.serializeUrl(t.extractedUrl),
this.serializeUrl(t.urlAfterRedirects), t.targetSnapshot!);
eventsSubject.next(routesRecognized);
}));
} else {
const processPreviousUrl = urlTransition && this.rawUrlTree &&
this.urlHandlingStrategy.shouldProcessUrl(this.rawUrlTree);
/* When the current URL shouldn't be processed, but the previous one was,
* we handle this "error condition" by navigating to the previously
* successful URL, but leaving the URL intact.*/
if (processPreviousUrl) {
const {id, extractedUrl, source, restoredState, extras} = t;
const navStart = new NavigationStart(
id, this.serializeUrl(extractedUrl), source, restoredState);
eventsSubject.next(navStart);
const targetSnapshot =
createEmptyState(extractedUrl, this.rootComponentType).snapshot;
return of({
...t,
targetSnapshot,
urlAfterRedirects: extractedUrl,
extras: {...extras, skipLocationChange: false, replaceUrl: false},
});
} else {
/* When neither the current or previous URL can be processed, do nothing
* other than update router's internal reference to the current "settled"
* URL. This way the next navigation will be coming from the current URL
* in the browser.
*/
this.rawUrlTree = t.rawUrl;
this.browserUrlTree = t.urlAfterRedirects;
t.resolve(null);
return EMPTY;
}
}
}),
// Before Preactivation
switchTap(t => {
const {
targetSnapshot,
id: navigationId,
extractedUrl: appliedUrlTree,
rawUrl: rawUrlTree,
extras: {skipLocationChange, replaceUrl}
} = t;
return this.hooks.beforePreactivation(targetSnapshot!, {
navigationId,
appliedUrlTree,
rawUrlTree,
skipLocationChange: !!skipLocationChange,
replaceUrl: !!replaceUrl,
});
}),
// --- GUARDS ---
tap(t => {
const guardsStart = new GuardsCheckStart(
t.id, this.serializeUrl(t.extractedUrl),
this.serializeUrl(t.urlAfterRedirects), t.targetSnapshot!);
this.triggerEvent(guardsStart);
}),
map(t => ({
...t,
guards: getAllRouteGuards(
t.targetSnapshot!, t.currentSnapshot, this.rootContexts)
})),
checkGuards(this.ngModule.injector, (evt: Event) => this.triggerEvent(evt)),
tap(t => {
if (isUrlTree(t.guardsResult)) {
const error: Error&{url?: UrlTree} = navigationCancelingError(
`Redirecting to "${this.serializeUrl(t.guardsResult)}"`);
error.url = t.guardsResult;
throw error;
}
const guardsEnd = new GuardsCheckEnd(
t.id, this.serializeUrl(t.extractedUrl),
this.serializeUrl(t.urlAfterRedirects), t.targetSnapshot!,
!!t.guardsResult);
this.triggerEvent(guardsEnd);
}),
filter(t => {
if (!t.guardsResult) {
this.restoreHistory(t);
this.cancelNavigationTransition(t, '');
return false;
}
return true;
}),
// --- RESOLVE ---
switchTap(t => {
if (t.guards.canActivateChecks.length) {
return of(t).pipe(
tap(t => {
const resolveStart = new ResolveStart(
t.id, this.serializeUrl(t.extractedUrl),
this.serializeUrl(t.urlAfterRedirects), t.targetSnapshot!);
this.triggerEvent(resolveStart);
}),
switchMap(t => {
let dataResolved = false;
return of(t).pipe(
resolveData(
this.paramsInheritanceStrategy, this.ngModule.injector),
tap({
next: () => dataResolved = true,
complete: () => {
if (!dataResolved) {
this.restoreHistory(t);
this.cancelNavigationTransition(
t,
`At least one route resolver didn't emit any value.`);
}
}
}),
);
}),
tap(t => {
const resolveEnd = new ResolveEnd(
t.id, this.serializeUrl(t.extractedUrl),
this.serializeUrl(t.urlAfterRedirects), t.targetSnapshot!);
this.triggerEvent(resolveEnd);
}));
}
return undefined;
}),
// --- AFTER PREACTIVATION ---
switchTap((t: NavigationTransition) => {
const {
targetSnapshot,
id: navigationId,
extractedUrl: appliedUrlTree,
rawUrl: rawUrlTree,
extras: {skipLocationChange, replaceUrl}
} = t;
return this.hooks.afterPreactivation(targetSnapshot!, {
navigationId,
appliedUrlTree,
rawUrlTree,
skipLocationChange: !!skipLocationChange,
replaceUrl: !!replaceUrl,
});
}),
map((t: NavigationTransition) => {
const targetRouterState = createRouterState(
this.routeReuseStrategy, t.targetSnapshot!, t.currentRouterState);
return ({...t, targetRouterState});
}),
/* Once here, we are about to activate syncronously. The assumption is this
will succeed, and user code may read from the Router service. Therefore
before activation, we need to update router properties storing the current
URL and the RouterState, as well as updated the browser URL. All this should
happen *before* activating. */
tap((t: NavigationTransition) => {
this.currentUrlTree = t.urlAfterRedirects;
this.rawUrlTree =
this.urlHandlingStrategy.merge(t.urlAfterRedirects, t.rawUrl);
(this as {routerState: RouterState}).routerState = t.targetRouterState!;
if (this.urlUpdateStrategy === 'deferred') {
if (!t.extras.skipLocationChange) {
this.setBrowserUrl(this.rawUrlTree, t);
}
this.browserUrlTree = t.urlAfterRedirects;
}
}),
activateRoutes(
this.rootContexts, this.routeReuseStrategy,
(evt: Event) => this.triggerEvent(evt)),
tap({
next() {
completed = true;
},
complete() {
completed = true;
}
}),
finalize(() => {
/* When the navigation stream finishes either through error or success, we
* set the `completed` or `errored` flag. However, there are some situations
* where we could get here without either of those being set. For instance, a
* redirect during NavigationStart. Therefore, this is a catch-all to make
* sure the NavigationCancel
* event is fired when a navigation gets cancelled but not caught by other
* means. */
if (!completed && !errored) {
const cancelationReason = `Navigation ID ${
t.id} is not equal to the current navigation id ${this.navigationId}`;
if (this.canceledNavigationResolution === 'replace') {
// Must reset to current URL tree here to ensure history.state is set. On
// a fresh page load, if a new navigation comes in before a successful
// navigation completes, there will be nothing in
// history.state.navigationId. This can cause sync problems with
// AngularJS sync code which looks for a value here in order to determine
// whether or not to handle a given popstate event or to leave it to the
// Angular router.
this.restoreHistory(t);
this.cancelNavigationTransition(t, cancelationReason);
} else {
// We cannot trigger a `location.historyGo` if the
// cancellation was due to a new navigation before the previous could
// complete. This is because `location.historyGo` triggers a `popstate`
// which would also trigger another navigation. Instead, treat this as a
// redirect and do not reset the state.
this.cancelNavigationTransition(t, cancelationReason);
// TODO(atscott): The same problem happens here with a fresh page load
// and a new navigation before that completes where we won't set a page
// id.
}
}
// currentNavigation should always be reset to null here. If navigation was
// successful, lastSuccessfulTransition will have already been set. Therefore
// we can safely set currentNavigation to null here.
this.currentNavigation = null;
}),
catchError((e) => {
// TODO(atscott): The NavigationTransition `t` used here does not accurately
// reflect the current state of the whole transition because some operations
// return a new object rather than modifying the one in the outermost
// `switchMap`.
// The fix can likely be to:
// 1. Rename the outer `t` variable so it's not shadowed all the time and
// confusing
// 2. Keep reassigning to the outer variable after each stage to ensure it
// gets updated. Or change the implementations to not return a copy.
// Not changed yet because it affects existing code and would need to be
// tested more thoroughly.
errored = true;
/* This error type is issued during Redirect, and is handled as a
* cancellation rather than an error. */
if (isNavigationCancelingError(e)) {
const redirecting = isUrlTree(e.url);
if (!redirecting) {
// Set property only if we're not redirecting. If we landed on a page and
// redirect to `/` route, the new navigation is going to see the `/`
// isn't a change from the default currentUrlTree and won't navigate.
// This is only applicable with initial navigation, so setting
// `navigated` only when not redirecting resolves this scenario.
this.navigated = true;
this.restoreHistory(t, true);
}
const navCancel = new NavigationCancel(
t.id, this.serializeUrl(t.extractedUrl), e.message);
eventsSubject.next(navCancel);
// When redirecting, we need to delay resolving the navigation
// promise and push it to the redirect navigation