715 Commits

Author SHA1 Message Date
urugator 64c8ebaf9f docs(router): fix misleading description of BaseRouteReuseStrategy (#47786)
The original description gave a false impression that only query params and fragment changes are ignored, while actually `routeParams` changes are ignored as well.
PR Close #47786
2022-10-19 20:12:23 +02:00
Jeremy Elbourn d8cfb7cbe5 refactor(router): remove unnecesary null (#47238)
These null values are unused and unecessary. I suspect it's a remnant from when the codebase was transpiled to Dart.

PR Close #47238
2022-09-06 09:57:38 -07:00
Andrew Scott 75df404467 feat(router): Create APIs for using Router without RouterModule (#47010)
This commit creates and exposes the APIs required to use the Angular Router without importing `RouterModule`.

The newly added APIs are tree-shakable and you can add features using special functions rather than using `ExtraOptions` to control the providers via an internal switch in Router code.

```
const appRoutes: Routes = [];
bootstrapApplication(AppComponent,
  {
    providers: [
      provideRouter(appRoutes,
        withDebugTracing(),     // enables debug tracing feature
        withInMemoryScrolling() // enables scrolling feature
    ]
  }
);
```

This "features" pattern allows for router behavior to evolve in a backwards compatible and tree-shakable way in the future. This approach also makes features more discoverable.

The newly added APIs can be used in any application today (doesn't require an application to be bootstrapped using standalone-based APIs).

Note: APIs added in this commit are released in the "Developer Preview" mode, read more about this mode in Angular docs: https://angular.io/guide/releases#developer-preview

PR Close #47010
2022-08-15 15:58:00 -07:00
Andrew Scott d4f44bde50 refactor(router): Provide easily patchable file for assigning relativeLinkResolution (#47136)
For context on the migration plan, see b/241955063

PR Close #47136
2022-08-12 16:11:34 +00:00
Emmanuel Roux 422323cee0 feat(router): improve typings for RouterLink boolean inputs (#47101)
Add wider typings to setter of preserveFragment, skipLocationChange and replaceUrl inputs of routerLink directives and coerce them to boolean

PR Close #47101
2022-08-12 13:28:38 +00:00
Andrew Scott 93289f9c76 refactor(router): Update error message when Router is provided twice (#47130)
The current error message is absolute in that it thinks there is only
one possible way to provide Router twice. In fact, you can get a new
instance of the Router in several ways so the error message should
indicate the exact failure case with a _potential_ cause.

Based on findings in thread https://github.com/angular/angular/commit/0cbbd6aeecda8ea994f1086727e580b813a53d79#commitcomment-80900192

PR Close #47130
2022-08-12 13:27:49 +00:00
Andrew Scott 2a43beec15 fix(router): Fix route recognition behavior with some versions of rxjs (#47098)
Some versions of rxjs cause the algorithm used in the Router to not recognize Route configs correctly.
This commit updates the algorithm to be compatible in the same way as other code locations internally.

Context:
https://github.com/angular/angular/commit/1160b8194f78141b40d1d4885ec182d033ff2659

fixes #47089

Note: This does not have a test because I was unable to identify the
version of rxjs that would cause a failure here.

PR Close #47098
2022-08-10 09:25:06 -07:00
Andrew Scott 0abb67af59 feat(router): allow guards and resolvers to be plain functions (#46684)
The current Router APIs require guards/resolvers to be present in the DI tree. This is because we want to treat all guards/resolvers equally and some may require dependencies. This requirement results in quite a lot of boilerplate for guards. Here are two examples:

```
const MY_GUARD = new InjectionToken<any>('my_guard');
…
providers: {provide: MY_GUARD, useValue: () => window.someGlobalState}
…
const route = {path: 'somePath', canActivate: [MY_GUARD]}
```

```
@Injectable({providedIn: 'root'})
export class MyGuardWithDependency {
  constructor(private myDep: MyDependency) {}

  canActivate() {
    return myDep.canActivate();
  }
}
…
const route = {path: 'somePath', canActivate: [MyGuardWithDependency]}
```

Notice that even when we want to write a simple guard that has no dependencies as in the first example, we still have to write either an InjectionToken or an Injectable class.

With this commit router guards and resolvers can be plain old functions.
 For example:

```
const route = {path: 'somePath', component: EditCmp, canDeactivate: [(component: EditCmp) => !component.hasUnsavedChanges]}
```

Additionally, these functions can still use Angular DI with `inject` from `@angular/core`.

```
const route = {path: 'somePath', canActivate: [() => inject(MyDependency).canActivate()]}
```

PR Close #46684
2022-08-05 10:36:46 -07:00
Andrew Scott d8cf78ba5e fix(router): Do not call preload method when not necessary (#47007)
In Angular 14, we introduced the `loadComponent` API for a `Route` to
allow lazy loading of a routed component in addition to the existing
`loadChildren` which allows lazy loading of child routes. As a result,
the `preload` method of the `PreloadingStrategy` needs to sometimes be
called even when there is a `canLoad` guard on the `Route`. `CanLoad`
guards block loading of child routes but _do not_ block loading of the
component.

This change updates the conditional checks in the internal preloader to
skip calling the `PreloadingStrategy.preload` when there is only a
`loadChildren` callback with a `canLoad` guard an no `loadComponent`.
In this case, the callback passed to the `preload` method is already
effectively a no-op so it's not necessary to call it at all.

resolves #47003

PR Close #47007
2022-08-02 09:38:28 -07:00
Andrew Scott f364378e4d fix(router): Use correct return type for provideRoutes function (#46941)
The provideRoutes function of the Router returns a Provider array and should not be typed as 'any'

PR Close #46941
2022-08-01 11:20:49 -07:00
Andrew Scott 8600732b09 feat(router): Expose the default matcher for Routes used by the Router (#46913)
This commit adds the `defaultUrlMatcher` from the Router to the public
API. `UrlMatcher` and `UrlMatchResult` are already in the public api so
the signature of the function as well as the return value are already
exposed. Any change to those or the implementation of `defaultUrlMatcher`
would already be breaking so there's no additional risk in exposing the
default matcher.

This function can be useful for developers who want to create a custom
matcher which builds on the default matcher of the Router. Currently,
the only way to do this would be to copy-paste the implementation.

fixes #35928

PR Close #46913
2022-08-01 11:19:33 -07:00
Andrew Scott 55febc1691 refactor(router): Remove unused ANALYZE_FOR_ENTRY_COMPONENTS (#46942)
`entryComponents` is a feature that is not used or necessary in Angular
anymore.

PR Close #46942
2022-08-01 11:18:09 -07:00
Alan Agius f4348360a6 docs(router): remove incorrect deprecation text in InitialNavigation (#46916)
Remove left over deprecation note.

PR Close #46916
2022-07-22 08:26:25 +00:00
Andrew Scott 8ac45a6264 refactor(router): Update internal INITIAL_NAVIGATION token to use an enum (#46925)
This updates the internal use of INITIAL_NAVIGATION to do two things:

1. Explicitly provide `Enabled` as the default for the token factory
2. Use an enum instead of a string to reduce bundle size

PR Close #46925
2022-07-22 08:25:37 +00:00
Emmanuel Roux 10289f1f6e feat(router): expose resolved route title (#46826)
Expose resolved route title from ActivatedRoute and ActivatedRouteSnapshot

PR Close #46826
2022-07-21 09:24:56 +00:00
Andrew Scott d583f85701 refactor(router): Update Router to be providedIn: 'root' (#46824)
This commit updates the Router itself to be `providedIn: 'root'` with a
factory function rather than provided in the `RouterModule`.

PR Close #46824
2022-07-20 11:36:04 -07:00
Andrew Kushnir 7a6509bdc1 refactor(core): NgModuleRef should not implement EnvironmentInjector interface (#46896)
This commit refactors the `NgModuleRef` implementation to drop functions required by the `EnvironmentInjector` interface. Previously the idea was that the `NgModuleRef` can act as an Injector to facilitate easier transition to standalone. However, from the mental model perspective, the `NgModuleRef` has the `injector` field, which is the correct injector reference and can be used is needed as an `EnvironmentInjector`.

PR Close #46896
2022-07-20 08:49:15 -07:00
Andrew Scott bde925bd42 refactor(router): Update TitleStrategy to useFactory (#46876)
The implementation of the `DefaultTitleStrategy` was modeled after the
existing strategy patterns in the Router. These patterns were developed
before the `providedIn` syntax for injectables. We can simplify the
model a lot by providing the default in the factory of the abstract
class.

Note that the other strategy patterns aren't touched in this PR due to
how long they've existed. Because they have been there for such a long
time, it's possible there will need to be some adjustments to code
if/when they are refactored to do the same.

PR Close #46876
2022-07-18 22:02:18 +00:00
Paul Gschwendtner d2b444a8a2 test: update tests to account for karma-jasmine v5.0.0
Karma jasmine updated the `jasmine-core` dependency. Jasmine is now more
strict when:

* The done callback is invoked multiple times
* The done callback is used, while a promise is also returned
* The done callback is treated as error when e.g. a number is returned
  as first argument. This was the case with `requestAnimationFrame`.
2022-07-18 19:19:00 +02:00
Andrew Scott c0f023f602 fix(router): Ensure target RouterStateSnapshot is defined in NavigationError (#46842)
The Router transition observable pipe keeps an outer reference to a `t`
variable for use in the `catchError` operator. However, this variable is
not updated with intermediate state. This commit fixes that so the
`catchError` can access properties that get updated in intermediate
states. Specifically, `RouterStateSnapshot` in the `NavigationError` for
now but could be more in the future.

PR Close #46842
2022-07-14 22:19:26 +00:00
Andrew Scott 26ea97688c feat(router): Make router directives standalone (#46758)
This commit makes the router directives standalone and refactors some of
the Router injectables to be `providedIn: 'root'` along with factory
functions for initialization.

PR Close #46758
2022-07-14 21:11:14 +00:00
Jessica Janiuk 9ad296a55f Revert "refactor(router): Remove use of OutletInjector" (#46775)
This reverts commit e288d87742.

PR Close #46775
2022-07-11 19:13:20 +00:00
Andrew Scott bf5bee6d43 refactor(router): move around some code to eliminate circular deps (#46752)
This commit eliminates some circular dependencies by moving around
interfaces and type guards.

PR Close #46752
2022-07-11 17:59:31 +00:00
Andrew Scott e8ae0fe3e9 fix(router): Fix cancellation code for canLoad rejections (#46752)
Before this commit, the `NavigationCancellationCode` would always be set
to `Redirect` when encountering a "navigationcancelingError". However,
this error can also be thrown when `CanLoad` guars reject. This commit
ensures these cancellation errors have a code as well so this mistake
cannot be made again.

PR Close #46752
2022-07-11 17:59:30 +00:00
Andrew Scott 647afb02b3 refactor(router): Simplify the prioritizeGuardValue logic (#46745)
The existing logic does something similar but in a more roundabout way.
It reads _the whole array_. If it encounters a pending value, it ignores
the remaining ones. If it hasn't encountered a pending value by the time
it hits false/UrlTree, it returns that result.

The new logic is the same, but reverses what we're looking for. Instead
of processing the whole array, we stop when we encounter an initial
value. When we encounter one that isn't `true`, that gets returned. If
we get to the end and everything was `true`, return `true`.

PR Close #46745

PR Close #46745
2022-07-11 16:55:58 +00:00
Jessica Janiuk a003dd8dc2 Revert "refactor(router): Simplify the prioritizeGuardValue logic" (#46759)
This reverts commit f32fface4763d789a8b7cc4f4489f98be4e1073a.

PR Close #46759
2022-07-08 22:27:01 +00:00
Andrew Scott 9acec3f0f7 refactor(router): Remove use of OutletInjector (#46755)
OutletInjector doesn't do anything special. Injector.create can be used instead

PR Close #46755
2022-07-08 21:56:01 +00:00
John Vandenberg c14c701775 docs: fix spelling (#46713)
PR Close #46713
2022-07-08 20:54:52 +00:00
Andrew Scott cee207ea11 refactor(router): Simplify the prioritizeGuardValue logic (#46745)
The existing logic does something similar but in a more roundabout way.
It reads _the whole array_. If it encounters a pending value, it ignores
the remaining ones. If it hasn't encountered a pending value by the time
it hits false/UrlTree, it returns that result.

The new logic is the same, but reverses what we're looking for. Instead
of processing the whole array, we stop when we encounter an initial
value. When we encounter one that isn't `true`, that gets returned. If
we get to the end and everything was `true`, return `true`.

PR Close #46745
2022-07-08 20:03:47 +00:00
Andrew Scott a4ce273e50 feat(router): Add the target RouterStateSnapshot to NavigationError (#46731)
This commit adds the target `RouterStateSnapshot` to the
`NavigationError` so error handlers/subscribers can more easily
determine which navigation failed, including the matched `Route` configs
for the navigation. This information was previously not available
(neither in `NavigationError` nor the `Router#getCurrentNavigation()`).

fixes #27626

PR Close #46731
2022-07-08 16:19:06 +00:00
Andrew Scott 6c1357dd7d feat(router): Add stable cancelation code to NavigationCancel event (#46675)
This commit adds a stable cancelation code to the `NavigationCancel`
event. This code is acceptable for use in production whereas parsing the
`reason` string is not. This allows developers to determine more
specifically _why_ a navigation was canceled and perform different
actions in different scenarios.

PR Close #46675
2022-07-06 07:42:24 -07:00
Andrew Scott dd3e0968ec refactor(router): Remove custom error message for invalid guards (#46678)
This custom error message for invalid guards requires a fair bit of
extra logic in several places. This change reduces special logic for an error
case that would fail anyways. Additionally, there were already a couple
places that _did not_ have this special error and we have not seen any
indication that there is more confusion for those (resolvers and canMatch).

PR Close #46678
2022-07-01 13:25:50 -07:00
Andrew Scott ee2e4917e6 docs: Update runGuardsAndResolvers documentation (#46671)
fixes  #46001

PR Close #46671
2022-07-01 10:19:22 -07:00
Andrew Scott e8c7dd10e9 fix(router): Ensure APP_INITIALIZER of enabledBlocking option completes (#46026)
Previously, if `initialNavigation` were set to `enabledBlocking`, the
Router's `APP_INITIALIZER` would never resolve if that initial
navigation failed. This results in the application load hanging and
never completing.

fixes #44355

PR Close #46026
2022-06-29 14:53:30 -07:00
Andrew Scott 36f46c6a9d refactor(router): Convert user-visible router errors to RuntimeError (#46562)
This commit refactors the Router errors to use the standard
`RuntimeError` used by the framework packages.

PR Close #46562
2022-06-29 12:50:23 -07:00
Andrew Scott ee39cf62bc fix(router): Ensure that new RouterOutlet instances work after old ones are destroyed (#46554)
There can be timing issues with removing an old outlet and creating a
new one to replace it. Before calling `onChildOutletDestroyed`, the
`RouterOutlet` will first check to ensure that it is still the one
registered for that outlet name.

Fixes #36711
Fixes #32453

PR Close #46554
2022-06-28 12:54:53 -07:00
Andrew Scott 2d713f5847 refactor(router): separate router initializer into different logical providers (#46215)
This change separates the router initializer into different providers.
While it does not actually change the tree-shakeablity or the public
API, it does move us towards a world that _could_ do this. That is,
instead of `initialNavigation: 'disabled'`, users could use
`provideDisabledInitialNavigation` in the `bootstrapApplication` call
and none of the code for `initialNavigation: 'enabledBlocking'` would be
included in the application.

PR Close #46215
2022-06-22 13:26:46 -07:00
Andrew Scott ae0a63ad48 refactor(router): Move preloading to tree-shakeable provider (#46215)
Extracting preloading to a provider moves us towards
thinking about a world where `ExtraOptions` doesn't exist to control
behaviors that are opt-in/opt-out. Instead, these behaviors could be
controlled by the presence (or lackthereof) of the providers which has
the functionality. This is relevant to a world in which we no longer
have the `RouterModule` but instead have something like `provideRouter`
where the features are tree-shakeable.

This change _does not_ make the `RouterPreloader` tree-shakeable inside
`RouterModule.forRoot` because the compiler cannot statically determine
whether it's needed. However, in the `provideRouter` world without
`forRoot`, preloading could be exposed through the provider function
instead, making the `RouterPreloader` and `PreloadingStrategy`
implementations tree-shakeable for those that don't use it (which is the
default - no preloading).

PR Close #46215
2022-06-22 13:26:46 -07:00
Andrew Scott 9a0e681c10 refactor(router): Extract router scroller into a tree-shakeable provider (#46215)
Extracting the scroller to a provider moves us towards
thinking about a world where `ExtraOptions` doesn't exist to control
behaviors that are opt-in/opt-out. Instead, these behaviors could be
controlled by the presence (or lackthereof) of the providers which has
the functionality. This is relevant to a world in which we no longer
have the `RouterModule` but instead have something like `provideRouter`
where the features are tree-shakeable.

This change does not affect the current `RouterModule.forRoot` behavior,
tree-shakeability of the option, or existence of the options related to
the router scroller (scrollPositionRestoriation, anchorScrolling,
scrollOffset).

PR Close #46215
2022-06-22 13:26:46 -07:00
Andrew Scott bfea80d19f refactor(router): Simplify location strategy providers (#46215)
Rather than using a `provideLocationStrategy` function, the `useHash`
can simply provide one strategy or another. The current factory function
does not change how the dependencies are used.

PR Close #46215
2022-06-22 13:26:46 -07:00
Andrew Scott d7a7983a0a refactor(router): Extract 'enableTracing' option to a provider (#46215)
Extracting the `'enableTracing'` option to a provider moves us towards
thinking about a world where `ExtraOptions` doesn't exist to control
behaviors that are opt-in/opt-out. Instead, these behaviors could be
controlled by the presence (or lackthereof) of the providers which has
the functionality. This is relevant to a world in which we no longer
have the `RouterModule` but instead have something like `provideRouter`
where the features are tree-shakeable.

This change does not affect the current `RouterModule.forRoot` behavior,
tree-shakeability of the option, or existence of `enableTracing` on the
`ExtraOptions`.

PR Close #46215
2022-06-22 13:26:46 -07:00
Dmitrij Kuba abe3759e24 fix(router): allow to return UrlTree from CanMatchFn (#46455)
Currently it's not possible to return plain `UrlTree` from `CanMatchFn`,
only wrapped `UrlTree` into Observable or Promise is allowed.
These changes allow to return `UrlTree` from `CanMatchFn`.

PR Close #46455
2022-06-22 13:25:23 -07:00
Andrew Scott f94c6f433d fix(router): Expose CanMatchFn as public API (#46394)
The `CanMatchFn` is already exposed in the type signature for `canMatch` on the
`Route`. This function type should already be exposed as public API but was
missed in the initial implementation because the older guards use the `any` type
instead.

PR Close #46394
2022-06-17 09:18:08 -07:00
Andrew Scott ce20ed067f fix(router): Ensure Route injector is created before running CanMatch guards (#46394)
Once a `Route` matches via the `match` or `path` property, we need to
immediately create the injector for the route (if it has providers)
before running the `CanMatch` guards. This is necessary because the
`CanMatch` guards might be provided in the `Route` providers.

Fixes #46386

PR Close #46394
2022-06-17 09:18:08 -07:00
markostanimirovic 13bffaec19 docs(router): fix errors in CanMatch examples (#46388)
This commit fixes compilation errors in CanMatch examples.

PR Close #46388
2022-06-16 09:33:22 -07:00
Andrew Scott 72e6a948bb refactor(router): Update recognize to use Observable instead of Promise (#46021)
The `Observable` chain is currenlty the most straightforward way to
handle navigation cancellations where we ensure that the cancelled
navigation does not continue to be processed. Until we design and
implement an alternative way to accomplish equivalent functionality,
we need to maintain the `Observable` chain wherever we might execute
user code. One reason for this isthat user code may contain redirects so we do not
want to execute those redirects if the navigation was already cancelled.

PR Close #46021
2022-06-13 22:53:49 +00:00
Andrew Scott de058bba99 feat(router): Add CanMatch guard to control whether a Route should match (#46021)
Currently we have two main types of guards:
`CanLoad`: decides if we can load a module (used with lazy loading)
`CanActivate` and friends. It decides if we can activate/deactivate a route.
So we always decide where we want to navigate first ("recognize") and create a new router state snapshot. And only then we run guards to check if the navigation should be allowed.
This doesn't handle one very important use case where we want to decide where to navigate based on some data (e.g., who the user is).
I suggest to add a new guard that allows us to do that.

```
[
  {path: 'home', component: AdminHomePage, canUse: [IsAdmin]},
  {path: 'home', component: SimpleHomePage}
]
```

Here, navigating to '/home' will render `AdminHomePage` if the user is an admin and will render 'SimpleHomePage' otherwise. Note that the url will remain '/home'.

With the introduction of standalone components and new features in the Router such as `loadComponent`,
there's a case for deprecating `CanLoad` and replacing it with the `CanMatch` guard. There are a few reasons for this:

* One of the intentions of having separate providers on a Route is that lazy
loading should not be an architectural feature of an application. It's an
optimization you do for code size. That is, there should not be an architectural
feature in the router to specifically control whether to lazy load something or
not based on conditions such as authentication. This is a slight nuanced
difference between the proposed canUse guard: this guard would control whether
you can use the route at all and as a side-effect, whether we download the code.
`CanLoad` only specified whether the code should be downloaded so canUse is more powerful and more appropriate.
* The naming of `CanLoad` will be potentially misunderstood for the `loadComponent` feature.
Because it applies to `loadChildren`, it feels reasonable to think that it will
also apply to `loadComponent`. This isn’t the case: since we don't need
to load the component until right before activation, we defer the
loading until all guards/resolvers have run.

When considering the removal of `CanLoad` and replacing it with `CanMatch`, this
does inform another decision that needed to be made: whether it makes sense for
`CanMatch` guards to return a UrlTree or if they should be restricted to just boolean.
The original thought was that no, these new guards should not allow returning UrlTree
because that significantly expands the intent of the feature from simply
“can I use the route” to “can I use this route, and if not, should I redirect?”
I now believe it should allowed to return `UrlTree` for several reasons:

* For feature parity with `CanLoad`
* Because whether we allow it as a return value or not, developers will still be
able to trigger a redirect from the guards using the `Router.navigate` function.
* Inevitably, there will be developers who disagree with the philosophical decision
to disallow `UrlTree` and we don’t necessarily have a compelling reason to refuse this as a feature.

Relates to #16211 - `CanMatch` instead of `CanActivate` would prevent
blank screen. Additional work is required to close this issue. This can
be accomplished by making the initial navigation result trackable (including
the redirects).
Resolves #14515
Replaces #16416
Resolves #34231
Resolves #17145
Resolves #12088

PR Close #46021
2022-06-13 22:53:49 +00:00
Andrew Scott 96f5c971ba refactor(router): Move runCanLoadGuards to same location as similar functions (#46021)
This commit moves the runCanLoadGuards to the same location as other guard execution functions

PR Close #46021
2022-06-13 22:53:49 +00:00
Andrew Scott caa2f3560d refactor(router): clean up internal hooks (#46321)
* beforePreactivation hook is unused
* The only place that uses afterPreactivation does not use the arguments

Not to say we won't want to provide hooks similar to this in the future,
but the current state is over-engineered for what it's being used for.

PR Close #46321
2022-06-10 15:23:57 +00:00
Adrien Crivelli 34890fb901 docs(router): Complete QueryParamsHandling documentation (#46286)
`QueryParamsHandling` has a third possibility which is the default behavior,
and it was not documented until now.

PR Close #46286
2022-06-08 12:40:56 -07:00