_id
stringlengths
21
254
text
stringlengths
1
93.7k
metadata
dict
angular/packages/router/test/router_link_active.spec.ts_0_1054
/** * @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.dev/license */ import {Component} from '@angular/core'; import {TestBed} from '@angular/core/testing'; import {Router, RouterLink, RouterLinkActive, provideRouter} from '@angular/router'; describe('RouterLinkActive', () => { it('removes initial active class even if never active', async () => { @Component({ standalone: true, imports: [RouterLinkActive, RouterLink], template: '<a class="active" routerLinkActive="active" routerLink="/abc123"></a>', }) class MyCmp {} TestBed.configureTestingModule({providers: [provideRouter([{path: '**', children: []}])]}); const fixture = TestBed.createComponent(MyCmp); fixture.autoDetectChanges(); await TestBed.inject(Router).navigateByUrl('/'); await fixture.whenStable(); expect(Array.from(fixture.nativeElement.querySelector('a').classList)).toEqual([]); }); });
{ "end_byte": 1054, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/router/test/router_link_active.spec.ts" }
angular/packages/router/test/apply_redirects.spec.ts_0_988
/** * @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.dev/license */ import {EnvironmentInjector, inject, Injectable, NgModuleRef} from '@angular/core'; import {fakeAsync, TestBed, tick} from '@angular/core/testing'; import {provideRouter, withRouterConfig} from '@angular/router'; import {firstValueFrom, Observable, of} from 'rxjs'; import {delay, map, tap} from 'rxjs/operators'; import {Route, Routes} from '../src/models'; import {recognize} from '../src/recognize'; import {Router} from '../src/router'; import {RouterConfigLoader} from '../src/router_config_loader'; import {ParamsInheritanceStrategy, RouterStateSnapshot} from '../src/router_state'; import { DefaultUrlSerializer, equalSegments, UrlSegment, UrlSegmentGroup, UrlTree, } from '../src/url_tree'; import {getLoadedRoutes, getProvidersInjector} from '../src/utils/config';
{ "end_byte": 988, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/router/test/apply_redirects.spec.ts" }
angular/packages/router/test/apply_redirects.spec.ts_990_8027
describe('redirects', () => { const serializer = new DefaultUrlSerializer(); it('should return the same url tree when no redirects', () => { checkRedirect( [ { path: 'a', component: ComponentA, children: [{path: 'b', component: ComponentB}], }, ], '/a/b', (t: UrlTree) => { expectTreeToBe(t, '/a/b'); }, ); }); it('should add new segments when needed', () => { checkRedirect( [ {path: 'a/b', redirectTo: 'a/b/c'}, {path: '**', component: ComponentC}, ], '/a/b', (t: UrlTree) => { expectTreeToBe(t, '/a/b/c'); }, ); }); it('should support redirecting with to an URL with query parameters', () => { const config: Routes = [ {path: 'single_value', redirectTo: '/dst?k=v1'}, {path: 'multiple_values', redirectTo: '/dst?k=v1&k=v2'}, {path: '**', component: ComponentA}, ]; checkRedirect(config, 'single_value', (t: UrlTree, state: RouterStateSnapshot) => { expectTreeToBe(t, '/dst?k=v1'); expect(state.root.queryParams).toEqual({k: 'v1'}); }); checkRedirect(config, 'multiple_values', (t: UrlTree) => expectTreeToBe(t, '/dst?k=v1&k=v2')); }); it('should handle positional parameters', () => { checkRedirect( [ {path: 'a/:aid/b/:bid', redirectTo: 'newa/:aid/newb/:bid'}, {path: '**', component: ComponentC}, ], '/a/1/b/2', (t: UrlTree) => { expectTreeToBe(t, '/newa/1/newb/2'); }, ); }); it('should throw when cannot handle a positional parameter', () => { recognize( TestBed.inject(EnvironmentInjector), null!, null, [{path: 'a/:id', redirectTo: 'a/:other'}], tree('/a/1'), serializer, ).subscribe( () => {}, (e) => { expect(e.message).toContain("Cannot redirect to 'a/:other'. Cannot find ':other'."); }, ); }); it('should pass matrix parameters', () => { checkRedirect( [ {path: 'a/:id', redirectTo: 'd/a/:id/e'}, {path: '**', component: ComponentC}, ], '/a;p1=1/1;p2=2', (t: UrlTree) => { expectTreeToBe(t, '/d/a;p1=1/1;p2=2/e'); }, ); }); it('should handle preserve secondary routes', () => { checkRedirect( [ {path: 'a/:id', redirectTo: 'd/a/:id/e'}, {path: 'c/d', component: ComponentA, outlet: 'aux'}, {path: '**', component: ComponentC}, ], '/a/1(aux:c/d)', (t: UrlTree) => { expectTreeToBe(t, '/d/a/1/e(aux:c/d)'); }, ); }); it('should redirect secondary routes', () => { checkRedirect( [ {path: 'a/:id', component: ComponentA}, {path: 'c/d', redirectTo: 'f/c/d/e', outlet: 'aux'}, {path: '**', component: ComponentC, outlet: 'aux'}, ], '/a/1(aux:c/d)', (t: UrlTree) => { expectTreeToBe(t, '/a/1(aux:f/c/d/e)'); }, ); }); it('should use the configuration of the route redirected to', () => { checkRedirect( [ { path: 'a', component: ComponentA, children: [{path: 'b', component: ComponentB}], }, {path: 'c', redirectTo: 'a'}, ], 'c/b', (t: UrlTree) => { expectTreeToBe(t, 'a/b'); }, ); }); it('should support redirects with both main and aux', () => { checkRedirect( [ { path: 'a', children: [ {path: 'bb', component: ComponentB}, {path: 'b', redirectTo: 'bb'}, {path: 'cc', component: ComponentC, outlet: 'aux'}, {path: 'b', redirectTo: 'cc', outlet: 'aux'}, ], }, ], 'a/(b//aux:b)', (t: UrlTree) => { expectTreeToBe(t, 'a/(bb//aux:cc)'); }, ); }); it('should support redirects with both main and aux (with a nested redirect)', () => { checkRedirect( [ { path: 'a', children: [ {path: 'bb', component: ComponentB}, {path: 'b', redirectTo: 'bb'}, { path: 'cc', component: ComponentC, outlet: 'aux', children: [ {path: 'dd', component: ComponentC}, {path: 'd', redirectTo: 'dd'}, ], }, {path: 'b', redirectTo: 'cc/d', outlet: 'aux'}, ], }, ], 'a/(b//aux:b)', (t: UrlTree) => { expectTreeToBe(t, 'a/(bb//aux:cc/dd)'); }, ); }); it('should redirect wild cards', () => { checkRedirect( [ {path: '404', component: ComponentA}, {path: '**', redirectTo: '/404'}, ], '/a/1(aux:c/d)', (t: UrlTree) => { expectTreeToBe(t, '/404'); }, ); }); it('should throw an error on infinite absolute redirect', () => { recognize( TestBed.inject(EnvironmentInjector), TestBed.inject(RouterConfigLoader), null, [{path: '**', redirectTo: '/404'}], tree('/'), new DefaultUrlSerializer(), ).subscribe({ next: () => fail('expected infinite redirect error'), error: (e) => { expect((e as Error).message).toMatch(/infinite redirect/); }, }); }); it('should support absolute redirects', () => { checkRedirect( [ { path: 'a', component: ComponentA, children: [{path: 'b/:id', redirectTo: '/absolute/:id?a=1&b=:b#f1'}], }, {path: '**', component: ComponentC}, ], '/a/b/1?b=2', (t: UrlTree) => { expectTreeToBe(t, '/absolute/1?a=1&b=2#f1'); }, ); }); it('should not create injector for Route if the route does not match', () => { const routes = [ {path: '', pathMatch: 'full' as const, providers: []}, { path: 'a', component: ComponentA, children: [{path: 'b', component: ComponentB}], }, ]; checkRedirect(routes, '/a/b', (t: UrlTree) => { expectTreeToBe(t, '/a/b'); expect(getProvidersInjector(routes[0])).not.toBeDefined(); }); }); it('should create injectors for partial Route route matches', () => { const routes = [ { path: 'a', component: ComponentA, providers: [], }, {path: 'doesNotMatch', providers: []}, ]; recognize( TestBed.inject(EnvironmentInjector), null!, null, routes, tree('a/b/c'), serializer, ).subscribe({ next: () => { throw 'Should not be reached'; }, error: () => { // The 'a' segment matched, so we needed to create the injector for the `Route` expect(getProvidersInjector(routes[0])).toBeDefined(); // The second `Route` did not match at all so we should not create an injector for it expect(getProvidersInjector(routes[1])).not.toBeDefined(); }, }); });
{ "end_byte": 8027, "start_byte": 990, "url": "https://github.com/angular/angular/blob/main/packages/router/test/apply_redirects.spec.ts" }
angular/packages/router/test/apply_redirects.spec.ts_8031_9066
it('should support CanMatch providers on the route', () => { @Injectable({providedIn: 'root'}) class CanMatchGuard { canMatch() { return true; } } const routes = [ { path: 'a', component: ComponentA, canMatch: [CanMatchGuard], providers: [CanMatchGuard], }, { path: 'a', component: ComponentA, providers: [], }, ]; recognize( TestBed.inject(EnvironmentInjector), null!, null, routes, tree('a'), serializer, ).subscribe({ next: () => { // The 'a' segment matched, so we needed to create the injector for the `Route` expect(getProvidersInjector(routes[0])).toBeDefined(); // The second `Route` did not match because the first did so we should not create an // injector for it expect(getProvidersInjector(routes[1])).not.toBeDefined(); }, error: () => { throw 'Should not be reached'; }, }); });
{ "end_byte": 9066, "start_byte": 8031, "url": "https://github.com/angular/angular/blob/main/packages/router/test/apply_redirects.spec.ts" }
angular/packages/router/test/apply_redirects.spec.ts_9070_17674
describe('lazy loading', () => { it('should load config on demand', () => { const loadedConfig = { routes: [{path: 'b', component: ComponentB}], injector: TestBed.inject(EnvironmentInjector), }; const loader: Pick<RouterConfigLoader, 'loadChildren'> = { loadChildren: (injector: any, p: any) => { if (injector !== TestBed.inject(EnvironmentInjector)) throw 'Invalid Injector'; return of(loadedConfig); }, }; const config: Routes = [ {path: 'a', component: ComponentA, loadChildren: jasmine.createSpy('children')}, ]; recognize( TestBed.inject(EnvironmentInjector), <any>loader, null, config, tree('a/b'), serializer, ).forEach(({tree}) => { expectTreeToBe(tree, '/a/b'); expect(getLoadedRoutes(config[0])).toBe(loadedConfig.routes); }); }); it('should handle the case when the loader errors', () => { const loader: Pick<RouterConfigLoader, 'loadChildren'> = { loadChildren: (p: any) => new Observable((obs) => obs.error(new Error('Loading Error'))), }; const config = [ {path: 'a', component: ComponentA, loadChildren: jasmine.createSpy('children')}, ]; recognize( TestBed.inject(EnvironmentInjector), <any>loader, null, config, tree('a/b'), serializer, ).subscribe( () => {}, (e) => { expect(e.message).toEqual('Loading Error'); }, ); }); it('should load when all canLoad guards return true', () => { const loadedConfig = { routes: [{path: 'b', component: ComponentB}], injector: TestBed.inject(EnvironmentInjector), }; const loader: Pick<RouterConfigLoader, 'loadChildren'> = { loadChildren: (injector: any, p: any) => of(loadedConfig), }; const config = [ { path: 'a', component: ComponentA, canLoad: [() => true, () => true], loadChildren: jasmine.createSpy('children'), }, ]; recognize( TestBed.inject(EnvironmentInjector), <any>loader, null, config, tree('a/b'), serializer, ).forEach(({tree: r}) => { expectTreeToBe(r, '/a/b'); }); }); it('should not load when any canLoad guards return false', () => { const loadedConfig = { routes: [{path: 'b', component: ComponentB}], injector: TestBed.inject(EnvironmentInjector), }; const loader: Pick<RouterConfigLoader, 'loadChildren'> = { loadChildren: (injector: any, p: any) => of(loadedConfig), }; const config = [ { path: 'a', component: ComponentA, canLoad: [() => true, () => false], loadChildren: jasmine.createSpy('children'), }, ]; recognize( TestBed.inject(EnvironmentInjector), <any>loader, null, config, tree('a/b'), serializer, ).subscribe( () => { throw 'Should not reach'; }, (e) => { expect(e.message).toEqual( `NavigationCancelingError: Cannot load children because the guard of the route "path: 'a'" returned false`, ); }, ); }); it('should not load when any canLoad guards is rejected (promises)', () => { const loadedConfig = { routes: [{path: 'b', component: ComponentB}], injector: TestBed.inject(EnvironmentInjector), }; const loader: Pick<RouterConfigLoader, 'loadChildren'> = { loadChildren: (injector: any, p: any) => of(loadedConfig), }; const config = [ { path: 'a', component: ComponentA, canLoad: [() => Promise.resolve(true), () => Promise.reject('someError')], loadChildren: jasmine.createSpy('children'), }, ]; recognize( TestBed.inject(EnvironmentInjector), <any>loader, null, config, tree('a/b'), serializer, ).subscribe( () => { throw 'Should not reach'; }, (e) => { expect(e).toEqual('someError'); }, ); }); it('should work with objects implementing the CanLoad interface', () => { const loadedConfig = { routes: [{path: 'b', component: ComponentB}], injector: TestBed.inject(EnvironmentInjector), }; const loader: Pick<RouterConfigLoader, 'loadChildren'> = { loadChildren: (injector: any, p: any) => of(loadedConfig), }; const config = [ { path: 'a', component: ComponentA, canLoad: [() => Promise.resolve(true)], loadChildren: jasmine.createSpy('children'), }, ]; recognize( TestBed.inject(EnvironmentInjector), <any>loader, null, config, tree('a/b'), serializer, ).subscribe( ({tree: r}) => { expectTreeToBe(r, '/a/b'); }, (e) => { throw 'Should not reach'; }, ); }); it('should pass UrlSegments to functions implementing the canLoad guard interface', () => { const loadedConfig = { routes: [{path: 'b', component: ComponentB}], injector: TestBed.inject(EnvironmentInjector), }; const loader: Pick<RouterConfigLoader, 'loadChildren'> = { loadChildren: (injector: any, p: any) => of(loadedConfig), }; let passedUrlSegments: UrlSegment[]; const guard = (route: Route, urlSegments: UrlSegment[]) => { passedUrlSegments = urlSegments; return true; }; const config = [ { path: 'a', component: ComponentA, canLoad: [guard], loadChildren: jasmine.createSpy('children'), }, ]; recognize( TestBed.inject(EnvironmentInjector), <any>loader, null, config, tree('a/b'), serializer, ).subscribe( ({tree: r}) => { expectTreeToBe(r, '/a/b'); expect(passedUrlSegments.length).toBe(2); expect(passedUrlSegments[0].path).toBe('a'); expect(passedUrlSegments[1].path).toBe('b'); }, (e) => { throw 'Should not reach'; }, ); }); it('should pass UrlSegments to objects implementing the canLoad guard interface', () => { const loadedConfig = { routes: [{path: 'b', component: ComponentB}], injector: TestBed.inject(EnvironmentInjector), }; const loader: Pick<RouterConfigLoader, 'loadChildren'> = { loadChildren: (injector: any, p: any) => of(loadedConfig), }; let passedUrlSegments: UrlSegment[]; const guard = { canLoad: (route: Route, urlSegments: UrlSegment[]) => { passedUrlSegments = urlSegments; return true; }, }; const injector = {get: (token: any) => (token === 'guard' ? guard : {injector})}; const config = [ { path: 'a', component: ComponentA, canLoad: ['guard'], loadChildren: jasmine.createSpy('children'), }, ]; recognize(<any>injector, <any>loader, null, config, tree('a/b'), serializer).subscribe( ({tree: r}) => { expectTreeToBe(r, '/a/b'); expect(passedUrlSegments.length).toBe(2); expect(passedUrlSegments[0].path).toBe('a'); expect(passedUrlSegments[1].path).toBe('b'); }, (e) => { throw 'Should not reach'; }, ); }); it('should work with absolute redirects', () => { const loadedConfig = { routes: [{path: '', component: ComponentB}], injector: TestBed.inject(EnvironmentInjector), }; const loader: Pick<RouterConfigLoader, 'loadChildren'> = { loadChildren: (injector: any, p: any) => of(loadedConfig), }; const config: Routes = [ {path: '', pathMatch: 'full', redirectTo: '/a'}, {path: 'a', loadChildren: jasmine.createSpy('children')}, ]; recognize( TestBed.inject(EnvironmentInjector), <any>loader, null, config, tree(''), serializer, ).forEach(({tree: r}) => { expectTreeToBe(r, 'a'); expect(getLoadedRoutes(config[1])).toBe(loadedConfig.routes); }); });
{ "end_byte": 17674, "start_byte": 9070, "url": "https://github.com/angular/angular/blob/main/packages/router/test/apply_redirects.spec.ts" }
angular/packages/router/test/apply_redirects.spec.ts_17680_26078
it('should load the configuration only once', () => { const loadedConfig = { routes: [{path: '', component: ComponentB}], injector: TestBed.inject(EnvironmentInjector), }; let called = false; const loader: Pick<RouterConfigLoader, 'loadChildren'> = { loadChildren: (injector: any, p: any) => { if (called) throw new Error('Should not be called twice'); called = true; return of(loadedConfig); }, }; const config: Routes = [{path: 'a', loadChildren: jasmine.createSpy('children')}]; recognize( TestBed.inject(EnvironmentInjector), <any>loader, null, config, tree('a?k1'), serializer, ).subscribe((r) => {}); recognize( TestBed.inject(EnvironmentInjector), <any>loader, null, config, tree('a?k2'), serializer, ).subscribe( ({tree: r}) => { expectTreeToBe(r, 'a?k2'); expect(getLoadedRoutes(config[0])).toBe(loadedConfig.routes); }, (e) => { throw 'Should not reach'; }, ); }); it('should load the configuration of a wildcard route', () => { const loadedConfig = { routes: [{path: '', component: ComponentB}], injector: TestBed.inject(EnvironmentInjector), }; const loader: Pick<RouterConfigLoader, 'loadChildren'> = { loadChildren: (injector: any, p: any) => of(loadedConfig), }; const config: Routes = [{path: '**', loadChildren: jasmine.createSpy('children')}]; recognize( TestBed.inject(EnvironmentInjector), <any>loader, null, config, tree('xyz'), serializer, ).forEach(({tree: r}) => { expect(getLoadedRoutes(config[0])).toBe(loadedConfig.routes); }); }); it('should not load the configuration of a wildcard route if there is a match', () => { const loadedConfig = { routes: [{path: '', component: ComponentB}], injector: TestBed.inject(EnvironmentInjector), }; const loader: jasmine.SpyObj<Pick<RouterConfigLoader, 'loadChildren'>> = jasmine.createSpyObj( 'loader', ['loadChildren'], ); loader.loadChildren.and.returnValue(of(loadedConfig).pipe(delay(0))); const config: Routes = [ {path: '', loadChildren: jasmine.createSpy('matchChildren')}, {path: '**', loadChildren: jasmine.createSpy('children')}, ]; recognize( TestBed.inject(EnvironmentInjector), <any>loader, null, config, tree(''), serializer, ).forEach(({tree: r}) => { expect(loader.loadChildren.calls.count()).toEqual(1); expect(loader.loadChildren.calls.first().args).not.toContain( jasmine.objectContaining({ loadChildren: jasmine.createSpy('children'), }), ); }); }); it('should load the configuration after a local redirect from a wildcard route', () => { const loadedConfig = { routes: [{path: '', component: ComponentB}], injector: TestBed.inject(EnvironmentInjector), }; const loader: Pick<RouterConfigLoader, 'loadChildren'> = { loadChildren: (injector: any, p: any) => of(loadedConfig), }; const config: Routes = [ {path: 'not-found', loadChildren: jasmine.createSpy('children')}, {path: '**', redirectTo: 'not-found'}, ]; recognize( TestBed.inject(EnvironmentInjector), <any>loader, null, config, tree('xyz'), serializer, ).forEach(({tree: r}) => { expect(getLoadedRoutes(config[0])).toBe(loadedConfig.routes); }); }); it('should load the configuration after an absolute redirect from a wildcard route', () => { const loadedConfig = { routes: [{path: '', component: ComponentB}], injector: TestBed.inject(EnvironmentInjector), }; const loader: Pick<RouterConfigLoader, 'loadChildren'> = { loadChildren: (injector: any, p: any) => of(loadedConfig), }; const config: Routes = [ {path: 'not-found', loadChildren: jasmine.createSpy('children')}, {path: '**', redirectTo: '/not-found'}, ]; recognize( TestBed.inject(EnvironmentInjector), <any>loader, null, config, tree('xyz'), serializer, ).forEach(({tree: r}) => { expect(getLoadedRoutes(config[0])).toBe(loadedConfig.routes); }); }); it('should load all matching configurations of empty path, including an auxiliary outlets', fakeAsync(() => { const loadedConfig = { routes: [{path: '', component: ComponentA}], injector: TestBed.inject(EnvironmentInjector), }; let loadCalls = 0; let loaded: string[] = []; const loader: Pick<RouterConfigLoader, 'loadChildren'> = { loadChildren: (injector: any, p: Route) => { loadCalls++; return of(loadedConfig).pipe( delay(100 * loadCalls), tap(() => loaded.push((p.loadChildren as jasmine.Spy).and.identity)), ); }, }; const config: Routes = [ {path: '', loadChildren: jasmine.createSpy('root')}, {path: '', loadChildren: jasmine.createSpy('aux'), outlet: 'popup'}, ]; recognize( TestBed.inject(EnvironmentInjector), <any>loader, null, config, tree(''), serializer, ).subscribe(); expect(loadCalls).toBe(1); tick(100); expect(loaded).toEqual(['root']); expect(loadCalls).toBe(2); tick(200); expect(loaded).toEqual(['root', 'aux']); })); it('should not try to load any matching configuration if previous load completed', fakeAsync(() => { const loadedConfig = { routes: [{path: 'a', component: ComponentA}], injector: TestBed.inject(EnvironmentInjector), }; let loadCalls = 0; let loaded: string[] = []; const loader: Pick<RouterConfigLoader, 'loadChildren'> = { loadChildren: (injector: any, p: Route) => { loadCalls++; return of(loadedConfig).pipe( delay(100 * loadCalls), tap(() => loaded.push((p.loadChildren as jasmine.Spy).and.identity)), ); }, }; const config: Routes = [{path: '**', loadChildren: jasmine.createSpy('children')}]; recognize( TestBed.inject(EnvironmentInjector), <any>loader, null, config, tree('xyz/a'), serializer, ).subscribe(); expect(loadCalls).toBe(1); tick(50); expect(loaded).toEqual([]); recognize( TestBed.inject(EnvironmentInjector), <any>loader, null, config, tree('xyz/b'), serializer, ).subscribe(); tick(50); expect(loaded).toEqual(['children']); expect(loadCalls).toBe(2); tick(200); recognize( TestBed.inject(EnvironmentInjector), <any>loader, null, config, tree('xyz/c'), serializer, ).subscribe(); tick(50); expect(loadCalls).toBe(2); tick(300); })); it('loads only the first match when two Routes with the same outlet have the same path', () => { const loadedConfig = { routes: [{path: '', component: ComponentA}], injector: TestBed.inject(EnvironmentInjector), }; let loadCalls = 0; let loaded: string[] = []; const loader: Pick<RouterConfigLoader, 'loadChildren'> = { loadChildren: (injector: any, p: Route) => { loadCalls++; return of(loadedConfig).pipe( tap(() => loaded.push((p.loadChildren as jasmine.Spy).and.identity)), ); }, }; const config: Routes = [ {path: 'a', loadChildren: jasmine.createSpy('first')}, {path: 'a', loadChildren: jasmine.createSpy('second')}, ]; recognize( TestBed.inject(EnvironmentInjector), <any>loader, null, config, tree('a'), serializer, ).subscribe(); expect(loadCalls).toBe(1); expect(loaded).toEqual(['first']); });
{ "end_byte": 26078, "start_byte": 17680, "url": "https://github.com/angular/angular/blob/main/packages/router/test/apply_redirects.spec.ts" }
angular/packages/router/test/apply_redirects.spec.ts_26084_27404
it('should load the configuration of empty root path if the entry is an aux outlet', fakeAsync(() => { const loadedConfig = { routes: [{path: '', component: ComponentA}], injector: TestBed.inject(EnvironmentInjector), }; let loaded: string[] = []; const rootDelay = 100; const auxDelay = 1; const loader: Pick<RouterConfigLoader, 'loadChildren'> = { loadChildren: (injector: any, p: Route) => { const delayMs = (p.loadChildren! as jasmine.Spy).and.identity === 'aux' ? auxDelay : rootDelay; return of(loadedConfig).pipe( delay(delayMs), tap(() => loaded.push((p.loadChildren as jasmine.Spy).and.identity)), ); }, }; const config: Routes = [ // Define aux route first so it matches before the primary outlet {path: 'modal', loadChildren: jasmine.createSpy('aux'), outlet: 'popup'}, {path: '', loadChildren: jasmine.createSpy('root')}, ]; recognize( TestBed.inject(EnvironmentInjector), <any>loader, null, config, tree('(popup:modal)'), serializer, ).subscribe(); tick(auxDelay); tick(rootDelay); expect(loaded.sort()).toEqual(['aux', 'root'].sort()); })); });
{ "end_byte": 27404, "start_byte": 26084, "url": "https://github.com/angular/angular/blob/main/packages/router/test/apply_redirects.spec.ts" }
angular/packages/router/test/apply_redirects.spec.ts_27408_36110
describe('empty paths', () => { it('redirect from an empty path should work (local redirect)', () => { checkRedirect( [ { path: 'a', component: ComponentA, children: [{path: 'b', component: ComponentB}], }, {path: '', redirectTo: 'a'}, ], 'b', (t: UrlTree) => { expectTreeToBe(t, 'a/b'); }, ); }); it('redirect from an empty path should work (absolute redirect)', () => { checkRedirect( [ { path: 'a', component: ComponentA, children: [{path: 'b', component: ComponentB}], }, {path: '', redirectTo: '/a/b'}, ], '', (t: UrlTree) => { expectTreeToBe(t, 'a/b'); }, ); }); it('should redirect empty path route only when terminal', () => { const config: Routes = [ { path: 'a', component: ComponentA, children: [{path: 'b', component: ComponentB}], }, {path: '', redirectTo: 'a', pathMatch: 'full'}, ]; recognize( TestBed.inject(EnvironmentInjector), null!, null, config, tree('b'), serializer, ).subscribe( (_) => { throw 'Should not be reached'; }, (e) => { expect(e.message).toContain("Cannot match any routes. URL Segment: 'b'"); }, ); }); it('redirect from an empty path should work (nested case)', () => { checkRedirect( [ { path: 'a', component: ComponentA, children: [ {path: 'b', component: ComponentB}, {path: '', redirectTo: 'b'}, ], }, {path: '', redirectTo: 'a'}, ], '', (t: UrlTree) => { expectTreeToBe(t, 'a/b'); }, ); }); it('redirect to an empty path should work', () => { checkRedirect( [ {path: '', component: ComponentA, children: [{path: 'b', component: ComponentB}]}, {path: 'a', redirectTo: ''}, ], 'a/b', (t: UrlTree) => { expectTreeToBe(t, 'b'); }, ); }); describe('aux split is in the middle', () => { it('should create a new url segment (non-terminal)', () => { checkRedirect( [ { path: 'a', children: [ {path: 'b', component: ComponentB}, {path: 'c', component: ComponentC, outlet: 'aux'}, {path: '', redirectTo: 'c', outlet: 'aux'}, ], }, ], 'a/b', (t: UrlTree) => { expectTreeToBe(t, 'a/(b//aux:c)'); }, ); }); it('should create a new url segment (terminal)', () => { checkRedirect( [ { path: 'a', children: [ {path: 'b', component: ComponentB}, {path: 'c', component: ComponentC, outlet: 'aux'}, {path: '', pathMatch: 'full', redirectTo: 'c', outlet: 'aux'}, ], }, ], 'a/b', (t: UrlTree) => { expectTreeToBe(t, 'a/b'); }, ); }); }); describe('aux split after empty path parent', () => { it('should work with non-empty auxiliary path', () => { checkRedirect( [ { path: '', children: [ {path: 'a', component: ComponentA}, {path: 'c', component: ComponentC, outlet: 'aux'}, {path: 'b', redirectTo: 'c', outlet: 'aux'}, ], }, ], '(aux:b)', (t: UrlTree) => { expectTreeToBe(t, '(aux:c)'); }, ); }); it('should work with empty auxiliary path', () => { checkRedirect( [ { path: '', children: [ {path: 'a', component: ComponentA}, {path: 'c', component: ComponentC, outlet: 'aux'}, {path: '', redirectTo: 'c', outlet: 'aux'}, ], }, ], '', (t: UrlTree) => { expectTreeToBe(t, '(aux:c)'); }, ); }); it('should work with empty auxiliary path and matching primary', () => { checkRedirect( [ { path: '', children: [ {path: 'a', component: ComponentA}, {path: 'c', component: ComponentC, outlet: 'aux'}, {path: '', redirectTo: 'c', outlet: 'aux'}, ], }, ], 'a', (t: UrlTree) => { expect(t.toString()).toEqual('/a(aux:c)'); }, ); }); it('should work with aux outlets adjacent to and children of empty path at once', () => { checkRedirect( [ { path: '', component: ComponentA, children: [{path: 'b', outlet: 'b', component: ComponentB}], }, {path: 'c', outlet: 'c', component: ComponentC}, ], '(b:b//c:c)', (t: UrlTree) => { expect(t.toString()).toEqual('/(b:b//c:c)'); }, ); }); it('should work with children outlets within two levels of empty parents', () => { checkRedirect( [ { path: '', component: ComponentA, children: [ { path: '', component: ComponentB, children: [ {path: 'd', outlet: 'aux', redirectTo: 'c'}, {path: 'c', outlet: 'aux', component: ComponentC}, ], }, ], }, ], '(aux:d)', (t: UrlTree) => { expect(t.toString()).toEqual('/(aux:c)'); }, ); }); it('does not persist a primary segment beyond the boundary of a named outlet match', () => { const config: Routes = [ { path: '', component: ComponentA, outlet: 'aux', children: [{path: 'b', component: ComponentB, redirectTo: '/c'}], }, {path: 'c', component: ComponentC}, ]; recognize( TestBed.inject(EnvironmentInjector), null!, null, config, tree('/b'), serializer, ).subscribe( (_) => { throw 'Should not be reached'; }, (e) => { expect(e.message).toContain(`Cannot match any routes. URL Segment: 'b'`); }, ); }); }); describe('split at the end (no right child)', () => { it('should create a new child (non-terminal)', () => { checkRedirect( [ { path: 'a', children: [ {path: 'b', component: ComponentB}, {path: '', redirectTo: 'b'}, {path: 'c', component: ComponentC, outlet: 'aux'}, {path: '', redirectTo: 'c', outlet: 'aux'}, ], }, ], 'a', (t: UrlTree) => { expectTreeToBe(t, 'a/(b//aux:c)'); }, ); }); it('should create a new child (terminal)', () => { checkRedirect( [ { path: 'a', children: [ {path: 'b', component: ComponentB}, {path: '', redirectTo: 'b'}, {path: 'c', component: ComponentC, outlet: 'aux'}, {path: '', pathMatch: 'full', redirectTo: 'c', outlet: 'aux'}, ], }, ], 'a', (t: UrlTree) => { expectTreeToBe(t, 'a/(b//aux:c)'); }, ); }); it('should work only only primary outlet', () => { checkRedirect( [ { path: 'a', children: [ {path: 'b', component: ComponentB}, {path: '', redirectTo: 'b'}, {path: 'c', component: ComponentC, outlet: 'aux'}, ], }, ], 'a/(aux:c)', (t: UrlTree) => { expectTreeToBe(t, 'a/(b//aux:c)'); }, ); }); });
{ "end_byte": 36110, "start_byte": 27408, "url": "https://github.com/angular/angular/blob/main/packages/router/test/apply_redirects.spec.ts" }
angular/packages/router/test/apply_redirects.spec.ts_36116_43638
describe('split at the end (right child)', () => { it('should create a new child (non-terminal)', () => { checkRedirect( [ { path: 'a', children: [ {path: 'b', component: ComponentB, children: [{path: 'd', component: ComponentB}]}, {path: '', redirectTo: 'b'}, { path: 'c', component: ComponentC, outlet: 'aux', children: [{path: 'e', component: ComponentC}], }, {path: '', redirectTo: 'c', outlet: 'aux'}, ], }, ], 'a/(d//aux:e)', (t: UrlTree) => { expectTreeToBe(t, 'a/(b/d//aux:c/e)'); }, ); }); it('should not create a new child (terminal)', () => { const config: Routes = [ { path: 'a', children: [ {path: 'b', component: ComponentB, children: [{path: 'd', component: ComponentB}]}, {path: '', redirectTo: 'b'}, { path: 'c', component: ComponentC, outlet: 'aux', children: [{path: 'e', component: ComponentC}], }, {path: '', pathMatch: 'full', redirectTo: 'c', outlet: 'aux'}, ], }, ]; recognize( TestBed.inject(EnvironmentInjector), null!, null, config, tree('a/(d//aux:e)'), serializer, ).subscribe( (_) => { throw 'Should not be reached'; }, (e) => { expect(e.message).toContain("Cannot match any routes. URL Segment: 'a'"); }, ); }); }); }); describe('empty URL leftovers', () => { it('should not error when no children matching and no url is left', () => { checkRedirect( [{path: 'a', component: ComponentA, children: [{path: 'b', component: ComponentB}]}], '/a', (t: UrlTree) => { expectTreeToBe(t, 'a'); }, ); }); it('should not error when no children matching and no url is left (aux routes)', () => { checkRedirect( [ { path: 'a', component: ComponentA, children: [ {path: 'b', component: ComponentB}, {path: '', redirectTo: 'c', outlet: 'aux'}, {path: 'c', component: ComponentC, outlet: 'aux'}, ], }, ], '/a', (t: UrlTree) => { expectTreeToBe(t, 'a/(aux:c)'); }, ); }); it('should error when no children matching and some url is left', () => { recognize( TestBed.inject(EnvironmentInjector), null!, null, [{path: 'a', component: ComponentA, children: [{path: 'b', component: ComponentB}]}], tree('/a/c'), serializer, ).subscribe( (_) => { throw 'Should not be reached'; }, (e) => { expect(e.message).toContain("Cannot match any routes. URL Segment: 'a/c'"); }, ); }); }); describe('custom path matchers', () => { it('should use custom path matcher', () => { const matcher = (s: any, g: any, r: any) => { if (s[0].path === 'a') { return {consumed: s.slice(0, 2), posParams: {id: s[1]}}; } else { return null; } }; checkRedirect( [ { matcher: matcher, component: ComponentA, children: [{path: 'b', component: ComponentB}], }, ], '/a/1/b', (t: UrlTree) => { expectTreeToBe(t, 'a/1/b'); }, ); }); }); describe('multiple matches with empty path named outlets', () => { it('should work with redirects when other outlet comes before the one being activated', () => { recognize( TestBed.inject(EnvironmentInjector), null!, null, [ { path: '', children: [ {path: '', outlet: 'aux', redirectTo: 'b'}, {path: 'b', component: ComponentA, outlet: 'aux'}, {path: '', redirectTo: 'b', pathMatch: 'full'}, {path: 'b', component: ComponentB}, ], }, ], tree(''), serializer, ).subscribe( ({tree}) => { expect(tree.toString()).toEqual('/b(aux:b)'); expect(tree.root.children['primary'].toString()).toEqual('b'); expect(tree.root.children['aux']).toBeDefined(); expect(tree.root.children['aux'].toString()).toEqual('b'); }, () => { fail('should not be reached'); }, ); }); it('should prevent empty named outlets from appearing in leaves, resulting in odd tree url', () => { recognize( TestBed.inject(EnvironmentInjector), null!, null, [ { path: '', children: [ {path: '', component: ComponentA, outlet: 'aux'}, {path: '', redirectTo: 'b', pathMatch: 'full'}, {path: 'b', component: ComponentB}, ], }, ], tree(''), serializer, ).subscribe( ({tree}) => { expect(tree.toString()).toEqual('/b'); }, () => { fail('should not be reached'); }, ); }); it('should work when entry point is named outlet', () => { recognize( TestBed.inject(EnvironmentInjector), null!, null, [ {path: '', component: ComponentA}, {path: 'modal', component: ComponentB, outlet: 'popup'}, ], tree('(popup:modal)'), serializer, ).subscribe( ({tree}) => { expect(tree.toString()).toEqual('/(popup:modal)'); }, (e) => { fail('should not be reached' + e.message); }, ); }); }); describe('redirecting to named outlets', () => { it('should work when using absolute redirects', () => { checkRedirect( [ {path: 'a/:id', redirectTo: '/b/:id(aux:c/:id)'}, {path: 'b/:id', component: ComponentB}, {path: 'c/:id', component: ComponentC, outlet: 'aux'}, ], 'a/1;p=99', (t: UrlTree) => { expectTreeToBe(t, '/b/1;p=99(aux:c/1;p=99)'); }, ); }); it('should work when using absolute redirects (wildcard)', () => { checkRedirect( [ {path: 'b', component: ComponentB}, {path: 'c', component: ComponentC, outlet: 'aux'}, {path: '**', redirectTo: '/b(aux:c)'}, ], 'a/1', (t: UrlTree) => { expectTreeToBe(t, '/b(aux:c)'); }, ); }); it('should throw when using non-absolute redirects', () => { recognize( TestBed.inject(EnvironmentInjector), null!, null, [{path: 'a', redirectTo: 'b(aux:c)'}], tree('a'), serializer, ).subscribe( () => { throw new Error('should not be reached'); }, (e) => { expect(e.message).toContain( "Only absolute redirects can have named outlets. redirectTo: 'b(aux:c)'", ); }, ); }); });
{ "end_byte": 43638, "start_byte": 36116, "url": "https://github.com/angular/angular/blob/main/packages/router/test/apply_redirects.spec.ts" }
angular/packages/router/test/apply_redirects.spec.ts_43642_51926
describe('can use redirectTo as a function', () => { it('with a simple function returning a string', () => { checkRedirect( [ {path: 'a/b', redirectTo: () => 'other'}, {path: '**', component: ComponentC}, ], '/a/b', (t: UrlTree) => { expectTreeToBe(t, '/other'); }, ); }); it('with a simple function returning a UrlTree', () => { checkRedirect( [ { path: 'a/b', redirectTo: () => new UrlTree( new UrlSegmentGroup([], { 'primary': new UrlSegmentGroup( [new UrlSegment('a', {}), new UrlSegment('b', {}), new UrlSegment('c', {})], {}, ), }), ), }, {path: '**', component: ComponentC}, ], '/a/b', (t: UrlTree) => { expectTreeToBe(t, '/a/b/c'); }, ); }); it('with a function using inject and returning a UrlTree', () => { checkRedirect( [ {path: 'a/b', redirectTo: () => inject(Router).parseUrl('/a/b/c')}, {path: '**', component: ComponentC}, ], '/a/b', (t: UrlTree) => { expectTreeToBe(t, '/a/b/c'); }, ); }); it('can access query params and redirect using them', () => { checkRedirect( [ { path: 'a/b', redirectTo: ({queryParams}) => { const tree = inject(Router).parseUrl('other'); tree.queryParams = queryParams; return tree; }, }, {path: '**', component: ComponentC}, ], '/a/b?hl=en&q=hello', (t: UrlTree) => { expectTreeToBe(t, 'other?hl=en&q=hello'); }, ); }); it('with a function using inject and returning a UrlTree with params', () => { checkRedirect( [ {path: 'a/b', redirectTo: () => inject(Router).parseUrl('/a;a1=1,a2=2/b/c?qp=123')}, {path: '**', component: ComponentC}, ], '/a/b', (t: UrlTree) => { expectTreeToBe(t, '/a;a1=1,a2=2/b/c?qp=123'); }, ); }); it('receives positional params from the current route', () => { checkRedirect( [ { path: ':id1/:id2', redirectTo: ({params}) => inject(Router).parseUrl(`/redirect?id1=${params['id1']}&id2=${params['id2']}`), }, {path: '**', component: ComponentC}, ], '/a/b', (t: UrlTree) => { expectTreeToBe(t, 'redirect?id1=a&id2=b'); }, ); }); it('receives params from the parent route', () => { checkRedirect( [ { path: ':id1/:id2', children: [ { path: 'c', redirectTo: ({params}) => inject(Router).parseUrl(`/redirect?id1=${params['id1']}&id2=${params['id2']}`), }, ], }, {path: '**', component: ComponentC}, ], '/a/b/c', (t: UrlTree) => { expectTreeToBe(t, 'redirect?id1=a&id2=b'); }, ); }); it('receives data from the parent componentless route', () => { checkRedirect( [ { path: 'a/b', data: {data1: 'hello', data2: 'world'}, children: [ { path: 'c', redirectTo: ({data}) => `/redirect?id1=${data['data1']}&id2=${data['data2']}`, }, ], }, {path: '**', component: ComponentC}, ], '/a/b/c', (t: UrlTree) => { expectTreeToBe(t, 'redirect?id1=hello&id2=world'); }, ); }); it('does not receive data from the parent route with component (default paramsInheritanceStrategy is emptyOnly)', () => { checkRedirect( [ { path: 'a/b', data: {data1: 'hello', data2: 'world'}, component: ComponentA, children: [ { path: 'c', redirectTo: ({data}) => { expect(data['data1']).toBeUndefined(); expect(data['data2']).toBeUndefined(); return `/redirect`; }, }, ], }, {path: '**', component: ComponentC}, ], '/a/b/c', (t: UrlTree) => { expectTreeToBe(t, 'redirect'); }, ); }); it('has access to inherited data from all ancestor routes with paramsInheritanceStrategy always', () => { checkRedirect( [ { path: 'a', data: {data1: 'hello'}, component: ComponentA, children: [ { path: 'b', data: {data2: 'world'}, component: ComponentB, children: [ { path: 'c', redirectTo: ({data}) => { expect(data['data1']).toBe('hello'); expect(data['data2']).toBe('world'); return `/redirect`; }, }, ], }, ], }, {path: '**', component: ComponentC}, ], '/a/b/c', (t: UrlTree) => { expectTreeToBe(t, 'redirect'); }, 'always', ); }); it('has access to path params', () => { checkRedirect( [ { path: 'a', children: [ { path: 'b', redirectTo: ({params}) => `/redirect?k1=${params['k1']}&k2=${params['k2']}&k3=${params['k3']}&k4=${params['k4']}`, }, ], }, {path: '**', component: ComponentC}, ], '/a;k1=v1;k2=v2/b;k3=v3;k4=v4', (t: UrlTree) => { expectTreeToBe(t, 'redirect?k1=v1&k2=v2&k3=v3&k4=v4'); }, ); }); }); // internal failure b/165719418 it('does not fail with large configs', () => { const config: Routes = []; for (let i = 0; i < 400; i++) { config.push({path: 'no_match', component: ComponentB}); } config.push({path: 'match', component: ComponentA}); recognize( TestBed.inject(EnvironmentInjector), null!, null, config, tree('match'), serializer, ).forEach(({tree: r}) => { expectTreeToBe(r, 'match'); }); }); }); function checkRedirect( config: Routes, url: string, callback: (t: UrlTree, state: RouterStateSnapshot) => void, paramsInheritanceStrategy?: ParamsInheritanceStrategy, ): void { recognize( TestBed.inject(EnvironmentInjector), TestBed.inject(RouterConfigLoader), null, config, tree(url), new DefaultUrlSerializer(), paramsInheritanceStrategy, ).subscribe({ next: (v) => callback(v.tree, v.state), error: (e) => { throw e; }, }); } function tree(url: string): UrlTree { return new DefaultUrlSerializer().parse(url); } function expectTreeToBe(actual: UrlTree, expectedUrl: string): void { const expected = tree(expectedUrl); const serializer = new DefaultUrlSerializer(); const error = `"${serializer.serialize(actual)}" is not equal to "${serializer.serialize( expected, )}"`; compareSegments(actual.root, expected.root, error); expect(actual.queryParams).toEqual(expected.queryParams); expect(actual.fragment).toEqual(expected.fragment); } function compareSegments(actual: UrlSegmentGroup, expected: UrlSegmentGroup, error: string): void { expect(actual).toBeDefined(error); expect(equalSegments(actual.segments, expected.segments)).toEqual(true, error); expect(Object.keys(actual.children).length).toEqual(Object.keys(expected.children).length, error); Object.keys(expected.children).forEach((key) => { compareSegments(actual.children[key], expected.children[key], error); }); } class ComponentA {} class ComponentB {} class ComponentC {}
{ "end_byte": 51926, "start_byte": 43642, "url": "https://github.com/angular/angular/blob/main/packages/router/test/apply_redirects.spec.ts" }
angular/packages/router/test/page_title_strategy_spec.ts_0_6402
/** * @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.dev/license */ import {DOCUMENT} from '@angular/common'; import {provideLocationMocks} from '@angular/common/testing'; import {Component, inject, Inject, Injectable, NgModule} from '@angular/core'; import {takeUntilDestroyed} from '@angular/core/rxjs-interop'; import {fakeAsync, TestBed, tick} from '@angular/core/testing'; import { ActivatedRoute, provideRouter, ResolveFn, Router, RouterModule, RouterStateSnapshot, TitleStrategy, withRouterConfig, } from '@angular/router'; import {RouterTestingHarness} from '@angular/router/testing'; describe('title strategy', () => { describe('DefaultTitleStrategy', () => { let router: Router; let document: Document; beforeEach(() => { TestBed.configureTestingModule({ imports: [TestModule], providers: [ provideLocationMocks(), provideRouter([], withRouterConfig({paramsInheritanceStrategy: 'always'})), ], }); router = TestBed.inject(Router); document = TestBed.inject(DOCUMENT); }); it('sets page title from data', fakeAsync(() => { router.resetConfig([{path: 'home', title: 'My Application', component: BlankCmp}]); router.navigateByUrl('home'); tick(); expect(document.title).toBe('My Application'); })); it('sets page title from resolved data', fakeAsync(() => { router.resetConfig([{path: 'home', title: TitleResolver, component: BlankCmp}]); router.navigateByUrl('home'); tick(); expect(document.title).toBe('resolved title'); })); it('sets page title from resolved data function', fakeAsync(() => { router.resetConfig([{path: 'home', title: () => 'resolved title', component: BlankCmp}]); router.navigateByUrl('home'); tick(); expect(document.title).toBe('resolved title'); })); it('sets title with child routes', fakeAsync(() => { router.resetConfig([ { path: 'home', title: 'My Application', children: [{path: '', title: 'child title', component: BlankCmp}], }, ]); router.navigateByUrl('home'); tick(); expect(document.title).toBe('child title'); })); it('sets title with child routes and named outlets', fakeAsync(() => { router.resetConfig([ { path: 'home', title: 'My Application', children: [ {path: '', title: 'child title', component: BlankCmp}, {path: '', outlet: 'childaux', title: 'child aux title', component: BlankCmp}, ], }, {path: 'compose', component: BlankCmp, outlet: 'aux', title: 'compose'}, ]); router.navigateByUrl('home(aux:compose)'); tick(); expect(document.title).toBe('child title'); })); it('sets page title with inherited params', fakeAsync(() => { router.resetConfig([ { path: 'home', title: 'My Application', children: [ { path: '', title: TitleResolver, component: BlankCmp, }, ], }, ]); router.navigateByUrl('home'); tick(); expect(document.title).toBe('resolved title'); })); it('can get the title from the ActivatedRouteSnapshot', async () => { router.resetConfig([ { path: 'home', title: 'My Application', component: BlankCmp, }, ]); await router.navigateByUrl('home'); expect(router.routerState.snapshot.root.firstChild!.title).toEqual('My Application'); }); it('pushes updates through the title observable', async () => { @Component({template: '', standalone: true}) class HomeCmp { private readonly title$ = inject(ActivatedRoute).title.pipe(takeUntilDestroyed()); title?: string; constructor() { this.title$.subscribe((v) => (this.title = v)); } } const titleResolver: ResolveFn<string> = (route) => route.queryParams['id']; router.resetConfig([ { path: 'home', title: titleResolver, component: HomeCmp, runGuardsAndResolvers: 'paramsOrQueryParamsChange', }, ]); const harness = await RouterTestingHarness.create(); const homeCmp = await harness.navigateByUrl('/home?id=1', HomeCmp); expect(homeCmp.title).toEqual('1'); await harness.navigateByUrl('home?id=2'); expect(homeCmp.title).toEqual('2'); }); }); describe('custom strategies', () => { it('overriding the setTitle method', fakeAsync(() => { @Injectable({providedIn: 'root'}) class TemplatePageTitleStrategy extends TitleStrategy { constructor(@Inject(DOCUMENT) private readonly document: Document) { super(); } // Example of how setTitle could implement a template for the title override updateTitle(state: RouterStateSnapshot) { const title = this.buildTitle(state); this.document.title = `My Application | ${title}`; } } TestBed.configureTestingModule({ imports: [TestModule], providers: [ provideLocationMocks(), provideRouter([]), {provide: TitleStrategy, useClass: TemplatePageTitleStrategy}, ], }); const router = TestBed.inject(Router); const document = TestBed.inject(DOCUMENT); router.resetConfig([ { path: 'home', title: 'Home', children: [{path: '', title: 'Child', component: BlankCmp}], }, ]); router.navigateByUrl('home'); tick(); expect(document.title).toEqual('My Application | Child'); })); }); }); @Component({ template: '', standalone: false, }) export class BlankCmp {} @Component({ template: ` <router-outlet></router-outlet> <router-outlet name="aux"></router-outlet> `, standalone: false, }) export class RootCmp {} @NgModule({ declarations: [BlankCmp], imports: [RouterModule.forRoot([])], }) export class TestModule {} @Injectable({providedIn: 'root'}) export class TitleResolver { resolve() { return 'resolved title'; } }
{ "end_byte": 6402, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/router/test/page_title_strategy_spec.ts" }
angular/packages/router/test/directives/router_outlet.spec.ts_0_6014
/** * @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.dev/license */ import {CommonModule, NgForOf} from '@angular/common'; import { Component, inject, provideExperimentalZonelessChangeDetection, Input, Signal, Type, NgModule, } from '@angular/core'; import {ComponentFixture, fakeAsync, TestBed, tick} from '@angular/core/testing'; import { provideRouter, Router, RouterModule, RouterOutlet, withComponentInputBinding, ROUTER_OUTLET_DATA, } from '@angular/router/src'; import {RouterTestingHarness} from '@angular/router/testing'; import {InjectionToken} from '../../../core/src/di'; describe('router outlet name', () => { it('should support name binding', fakeAsync(() => { @Component({ standalone: true, template: '<router-outlet [name]="name"></router-outlet>', imports: [RouterOutlet], }) class RootCmp { name = 'popup'; } @Component({ template: 'popup component', standalone: true, }) class PopupCmp {} TestBed.configureTestingModule({ imports: [RouterModule.forRoot([{path: '', outlet: 'popup', component: PopupCmp}])], }); const router = TestBed.inject(Router); const fixture = createRoot(router, RootCmp); expect(fixture.nativeElement.innerHTML).toContain('popup component'); })); it('should be able to change the name of the outlet', fakeAsync(() => { @Component({ standalone: true, template: '<router-outlet [name]="name"></router-outlet>', imports: [RouterOutlet], }) class RootCmp { name = ''; } @Component({ template: 'hello world', standalone: true, }) class GreetingCmp {} @Component({ template: 'goodbye cruel world', standalone: true, }) class FarewellCmp {} TestBed.configureTestingModule({ imports: [ RouterModule.forRoot([ {path: '', outlet: 'greeting', component: GreetingCmp}, {path: '', outlet: 'farewell', component: FarewellCmp}, ]), ], }); const router = TestBed.inject(Router); const fixture = createRoot(router, RootCmp); expect(fixture.nativeElement.innerHTML).not.toContain('goodbye'); expect(fixture.nativeElement.innerHTML).not.toContain('hello'); fixture.componentInstance.name = 'greeting'; advance(fixture); expect(fixture.nativeElement.innerHTML).toContain('hello'); expect(fixture.nativeElement.innerHTML).not.toContain('goodbye'); fixture.componentInstance.name = 'goodbye'; advance(fixture); expect(fixture.nativeElement.innerHTML).toContain('goodbye'); expect(fixture.nativeElement.innerHTML).not.toContain('hello'); })); it('should support outlets in ngFor', fakeAsync(() => { @Component({ standalone: true, template: ` <div *ngFor="let outlet of outlets"> <router-outlet [name]="outlet"></router-outlet> </div> `, imports: [RouterOutlet, NgForOf], }) class RootCmp { outlets = ['outlet1', 'outlet2', 'outlet3']; } @Component({ template: 'component 1', standalone: true, }) class Cmp1 {} @Component({ template: 'component 2', standalone: true, }) class Cmp2 {} @Component({ template: 'component 3', standalone: true, }) class Cmp3 {} TestBed.configureTestingModule({ imports: [ RouterModule.forRoot([ {path: '1', outlet: 'outlet1', component: Cmp1}, {path: '2', outlet: 'outlet2', component: Cmp2}, {path: '3', outlet: 'outlet3', component: Cmp3}, ]), ], }); const router = TestBed.inject(Router); const fixture = createRoot(router, RootCmp); router.navigate([{outlets: {'outlet1': '1'}}]); advance(fixture); expect(fixture.nativeElement.innerHTML).toContain('component 1'); expect(fixture.nativeElement.innerHTML).not.toContain('component 2'); expect(fixture.nativeElement.innerHTML).not.toContain('component 3'); router.navigate([{outlets: {'outlet1': null, 'outlet2': '2', 'outlet3': '3'}}]); advance(fixture); expect(fixture.nativeElement.innerHTML).not.toContain('component 1'); expect(fixture.nativeElement.innerHTML).toMatch('.*component 2.*component 3'); // reverse the outlets fixture.componentInstance.outlets = ['outlet3', 'outlet2', 'outlet1']; router.navigate([{outlets: {'outlet1': '1', 'outlet2': '2', 'outlet3': '3'}}]); advance(fixture); expect(fixture.nativeElement.innerHTML).toMatch('.*component 3.*component 2.*component 1'); })); it('should not activate if route is changed', fakeAsync(() => { @Component({ standalone: true, template: '<div *ngIf="initDone"><router-outlet></router-outlet></div>', imports: [RouterOutlet, CommonModule], }) class ParentCmp { initDone = false; constructor() { setTimeout(() => (this.initDone = true), 1000); } } @Component({ template: 'child component', standalone: true, }) class ChildCmp {} TestBed.configureTestingModule({ imports: [ RouterModule.forRoot([ {path: 'parent', component: ParentCmp, children: [{path: 'child', component: ChildCmp}]}, ]), ], }); const router = TestBed.inject(Router); const fixture = createRoot(router, ParentCmp); advance(fixture, 250); router.navigate(['parent/child']); advance(fixture, 250); // Not contain because initDone is still false expect(fixture.nativeElement.innerHTML).not.toContain('child component'); advance(fixture, 1500); router.navigate(['parent']); advance(fixture, 1500); // Not contain because route was changed back to parent expect(fixture.nativeElement.innerHTML).not.toContain('child component'); })); });
{ "end_byte": 6014, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/router/test/directives/router_outlet.spec.ts" }
angular/packages/router/test/directives/router_outlet.spec.ts_6016_13626
describe('component input binding', () => { it('sets component inputs from matching query params', async () => { @Component({ template: '', standalone: false, }) class MyComponent { @Input() language?: string; } TestBed.configureTestingModule({ providers: [ provideRouter([{path: '**', component: MyComponent}], withComponentInputBinding()), ], }); const harness = await RouterTestingHarness.create(); const instance = await harness.navigateByUrl('/?language=english', MyComponent); expect(instance.language).toEqual('english'); await harness.navigateByUrl('/?language=french'); expect(instance.language).toEqual('french'); // Should set the input to undefined when the matching router data is removed await harness.navigateByUrl('/'); expect(instance.language).toEqual(undefined); await harness.navigateByUrl('/?notlanguage=doubletalk'); expect(instance.language).toEqual(undefined); }); it('sets component inputs from resolved and static data', async () => { @Component({ template: '', standalone: false, }) class MyComponent { @Input() resolveA?: string; @Input() dataA?: string; } TestBed.configureTestingModule({ providers: [ provideRouter( [ { path: '**', component: MyComponent, data: {'dataA': 'My static data'}, resolve: {'resolveA': () => 'My resolved data'}, }, ], withComponentInputBinding(), ), ], }); const harness = await RouterTestingHarness.create(); const instance = await harness.navigateByUrl('/', MyComponent); expect(instance.resolveA).toEqual('My resolved data'); expect(instance.dataA).toEqual('My static data'); }); it('sets component inputs from path params', async () => { @Component({ template: '', standalone: false, }) class MyComponent { @Input() language?: string; } TestBed.configureTestingModule({ providers: [ provideRouter([{path: '**', component: MyComponent}], withComponentInputBinding()), ], }); const harness = await RouterTestingHarness.create(); const instance = await harness.navigateByUrl('/x;language=english', MyComponent); expect(instance.language).toEqual('english'); }); it('when keys conflict, sets inputs based on priority: data > path params > query params', async () => { @Component({ template: '', standalone: false, }) class MyComponent { @Input() result?: string; } TestBed.configureTestingModule({ providers: [ provideRouter( [ { path: 'withData', component: MyComponent, data: {'result': 'from data'}, }, { path: 'withoutData', component: MyComponent, }, ], withComponentInputBinding(), ), ], }); const harness = await RouterTestingHarness.create(); let instance = await harness.navigateByUrl( '/withData;result=from path param?result=from query params', MyComponent, ); expect(instance.result).toEqual('from data'); // Same component, different instance because it's a different route instance = await harness.navigateByUrl( '/withoutData;result=from path param?result=from query params', MyComponent, ); expect(instance.result).toEqual('from path param'); instance = await harness.navigateByUrl('/withoutData?result=from query params', MyComponent); expect(instance.result).toEqual('from query params'); }); it('does not write multiple times if two sources of conflicting keys both update', async () => { let resultLog: Array<string | undefined> = []; @Component({ template: '', standalone: false, }) class MyComponent { @Input() set result(v: string | undefined) { resultLog.push(v); } } TestBed.configureTestingModule({ providers: [ provideRouter([{path: '**', component: MyComponent}], withComponentInputBinding()), ], }); const harness = await RouterTestingHarness.create(); await harness.navigateByUrl('/x', MyComponent); expect(resultLog).toEqual([undefined]); await harness.navigateByUrl('/x;result=from path param?result=from query params', MyComponent); expect(resultLog).toEqual([undefined, 'from path param']); }); it('Should have inputs available to all outlets after navigation', async () => { @Component({ template: '{{myInput}}', standalone: true, }) class MyComponent { @Input() myInput?: string; } @Component({ template: '<router-outlet/>', imports: [RouterOutlet], standalone: true, }) class OutletWrapper {} TestBed.configureTestingModule({ providers: [ provideRouter( [ { path: 'root', component: OutletWrapper, children: [{path: '**', component: MyComponent}], }, ], withComponentInputBinding(), ), ], }); const harness = await RouterTestingHarness.create('/root/child?myInput=1'); expect(harness.routeNativeElement!.innerText).toBe('1'); await harness.navigateByUrl('/root/child?myInput=2'); expect(harness.routeNativeElement!.innerText).toBe('2'); }); }); describe('injectors', () => { it('should always use environment injector from route hierarchy and not inherit from outlet', async () => { let childTokenValue: any = null; const TOKEN = new InjectionToken<any>(''); @Component({ template: '', standalone: true, }) class Child { constructor() { childTokenValue = inject(TOKEN as any, {optional: true}); } } @NgModule({ providers: [{provide: TOKEN, useValue: 'some value'}], }) class ModWithProviders {} @Component({ template: '<router-outlet/>', imports: [RouterOutlet, ModWithProviders], standalone: true, }) class App {} TestBed.configureTestingModule({ providers: [provideRouter([{path: 'a', component: Child}])], }); const fixture = TestBed.createComponent(App); fixture.detectChanges(); await TestBed.inject(Router).navigateByUrl('/a'); fixture.detectChanges(); expect(childTokenValue).toEqual(null); }); it('should not get sibling providers', async () => { let childTokenValue: any = null; const TOKEN = new InjectionToken<any>(''); @Component({ template: '', standalone: true, }) class Child { constructor() { childTokenValue = inject(TOKEN, {optional: true}); } } @Component({ template: '<router-outlet/>', imports: [RouterOutlet], standalone: true, }) class App {} TestBed.configureTestingModule({ providers: [ provideRouter([ {path: 'a', providers: [{provide: TOKEN, useValue: 'a value'}], component: Child}, {path: 'b', component: Child}, ]), ], }); const fixture = TestBed.createComponent(App); fixture.detectChanges(); await TestBed.inject(Router).navigateByUrl('/a'); fixture.detectChanges(); expect(childTokenValue).toEqual('a value'); await TestBed.inject(Router).navigateByUrl('/b'); fixture.detectChanges(); expect(childTokenValue).toEqual(null); }); });
{ "end_byte": 13626, "start_byte": 6016, "url": "https://github.com/angular/angular/blob/main/packages/router/test/directives/router_outlet.spec.ts" }
angular/packages/router/test/directives/router_outlet.spec.ts_13628_17542
describe('router outlet data', () => { it('is injectable even when not set', async () => { @Component({template: '', standalone: true}) class MyComponent { data = inject(ROUTER_OUTLET_DATA); } @Component({template: '<router-outlet />', standalone: true, imports: [RouterOutlet]}) class App {} TestBed.configureTestingModule({ providers: [provideRouter([{path: '**', component: MyComponent}])], }); const fixture = TestBed.createComponent(App); await TestBed.inject(Router).navigateByUrl('/'); fixture.detectChanges(); const routedComponent = fixture.debugElement.query( (v) => v.componentInstance instanceof MyComponent, ).componentInstance as MyComponent; expect(routedComponent.data()).toEqual(undefined); }); it('can set and update value', async () => { @Component({template: '', standalone: true}) class MyComponent { data = inject(ROUTER_OUTLET_DATA); } TestBed.configureTestingModule({ providers: [ provideRouter([{path: '**', component: MyComponent}]), provideExperimentalZonelessChangeDetection(), ], }); const harness = await RouterTestingHarness.create(); harness.fixture.componentInstance.routerOutletData.set('initial'); const routedComponent = await harness.navigateByUrl('/', MyComponent); expect(routedComponent.data()).toEqual('initial'); harness.fixture.componentInstance.routerOutletData.set('new'); await harness.fixture.whenStable(); expect(routedComponent.data()).toEqual('new'); }); it('overrides parent provided data with nested', async () => { @Component({ imports: [RouterOutlet], standalone: true, template: `{{outletData()}}|<router-outlet [routerOutletData]="'child'" />`, }) class Child { readonly outletData = inject(ROUTER_OUTLET_DATA); } @Component({ standalone: true, template: '{{outletData()}}', }) class GrandChild { readonly outletData = inject(ROUTER_OUTLET_DATA); } TestBed.configureTestingModule({ providers: [ provideRouter([ { path: 'child', component: Child, children: [{path: 'grandchild', component: GrandChild}], }, ]), ], }); const harness = await RouterTestingHarness.create(); harness.fixture.componentInstance.routerOutletData.set('parent'); await harness.navigateByUrl('/child/grandchild'); expect(harness.routeNativeElement?.innerText).toContain('parent|child'); }); it('does not inherit ancestor data when not provided in nested', async () => { @Component({ imports: [RouterOutlet], standalone: true, template: `{{outletData()}}|<router-outlet />`, }) class Child { readonly outletData = inject(ROUTER_OUTLET_DATA); } @Component({ standalone: true, template: '{{outletData() ?? "not provided"}}', }) class GrandChild { readonly outletData = inject(ROUTER_OUTLET_DATA); } TestBed.configureTestingModule({ providers: [ provideRouter([ { path: 'child', component: Child, children: [{path: 'grandchild', component: GrandChild}], }, ]), ], }); const harness = await RouterTestingHarness.create(); harness.fixture.componentInstance.routerOutletData.set('parent'); await harness.navigateByUrl('/child/grandchild'); expect(harness.routeNativeElement?.innerText).toContain('parent|not provided'); }); }); function advance(fixture: ComponentFixture<unknown>, millis?: number): void { tick(millis); fixture.detectChanges(); } function createRoot<T>(router: Router, type: Type<T>): ComponentFixture<T> { const f = TestBed.createComponent(type); advance(f); router.initialNavigation(); advance(f); return f; }
{ "end_byte": 17542, "start_byte": 13628, "url": "https://github.com/angular/angular/blob/main/packages/router/test/directives/router_outlet.spec.ts" }
angular/packages/router/test/operators/prioritized_guard_value.spec.ts_0_6441
/** * @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.dev/license */ import {TestBed} from '@angular/core/testing'; import {RouterModule} from '@angular/router'; import {TestScheduler} from 'rxjs/testing'; import {prioritizedGuardValue} from '../../src/operators/prioritized_guard_value'; import {Router} from '../../src/router'; describe('prioritizedGuardValue operator', () => { let testScheduler: TestScheduler; let router: Router; const TF = {T: true, F: false}; beforeEach(() => { TestBed.configureTestingModule({imports: [RouterModule.forRoot([])]}); }); beforeEach(() => { testScheduler = new TestScheduler(assertDeepEquals); }); beforeEach(() => { router = TestBed.inject(Router); }); it('should return true if all values are true', () => { testScheduler.run(({hot, cold, expectObservable}) => { const a = cold(' --(T|)', TF); const b = cold(' ----------(T|)', TF); const c = cold(' ------(T|)', TF); const source = hot('---o--', {o: [a, b, c]}); const expected = ' -------------T--'; expectObservable(source.pipe(prioritizedGuardValue())).toBe( expected, TF, /* an error here maybe */ ); }); }); it('should return false if observables to the left of false have produced a value', () => { testScheduler.run(({hot, cold, expectObservable}) => { const a = cold(' --(T|)', TF); const b = cold(' ----------(T|)', TF); const c = cold(' ------(F|)', TF); const source = hot('---o--', {o: [a, b, c]}); const expected = ' -------------F--'; expectObservable(source.pipe(prioritizedGuardValue())).toBe( expected, TF, /* an error here maybe */ ); }); }); it('should ignore results for unresolved sets of Observables', () => { testScheduler.run(({hot, cold, expectObservable}) => { const a = cold(' --(T|)', TF); const b = cold(' -------------(T|)', TF); const c = cold(' ------(F|)', TF); const z = cold(' ----(T|)', TF); const source = hot('---o----p----', {o: [a, b, c], p: [z]}); const expected = ' ------------T---'; expectObservable(source.pipe(prioritizedGuardValue())).toBe( expected, TF, /* an error here maybe */ ); }); }); it('should return UrlTree if higher priority guards have resolved', () => { testScheduler.run(({hot, cold, expectObservable}) => { const urlTree = router.parseUrl('/'); const urlLookup = {U: urlTree}; const a = cold(' --(T|)', TF); const b = cold(' ----------(U|)', urlLookup); const c = cold(' ------(T|)', TF); const source = hot('---o---', {o: [a, b, c]}); const expected = ' -------------U---'; expectObservable(source.pipe(prioritizedGuardValue())).toBe( expected, urlLookup, /* an error here maybe */ ); }); }); it('should return false even with UrlTree if UrlTree is lower priority', () => { testScheduler.run(({hot, cold, expectObservable}) => { const urlTree = router.parseUrl('/'); const urlLookup = {U: urlTree}; const a = cold(' --(T|)', TF); const b = cold(' ----------(F|)', TF); const c = cold(' ------(U|)', urlLookup); const source = hot('---o---', {o: [a, b, c]}); const expected = ' -------------F---'; expectObservable(source.pipe(prioritizedGuardValue())).toBe( expected, TF, /* an error here maybe */ ); }); }); it('should return UrlTree even after a false if the false is lower priority', () => { testScheduler.run(({hot, cold, expectObservable}) => { const urlTree = router.parseUrl('/'); const urlLookup = {U: urlTree}; const a = cold(' --(T|)', TF); const b = cold(' ----------(U|)', urlLookup); const c = cold(' ------(F|)', TF); const source = hot('---o---', {o: [a, b, c]}); const expected = ' -------------U----'; expectObservable(source.pipe(prioritizedGuardValue())).toBe( expected, urlLookup, /* an error here maybe */ ); }); }); it('should return the highest priority UrlTree', () => { testScheduler.run(({hot, cold, expectObservable}) => { const urlTreeU = router.parseUrl('/u'); const urlTreeR = router.parseUrl('/r'); const urlTreeL = router.parseUrl('/l'); const urlLookup = {U: urlTreeU, R: urlTreeR, L: urlTreeL}; const a = cold(' ----------(U|)', urlLookup); const b = cold(' -----(R|)', urlLookup); const c = cold(' --(L|)', urlLookup); const source = hot('---o---', {o: [a, b, c]}); const expected = ' -------------U---'; expectObservable(source.pipe(prioritizedGuardValue())).toBe( expected, urlLookup, /* an error here maybe */ ); }); }); it('should ignore invalid values', () => { testScheduler.run(({hot, cold, expectObservable}) => { const resultLookup = {T: true, U: undefined, S: 'I am not a valid guard result' as any}; const a = cold(' ----------(T|)', resultLookup); const b = cold(' -----(U|)', resultLookup); const c = cold(' -----(S|)', resultLookup); const d = cold(' --(T|)', resultLookup); const source = hot('---o---', {o: [a, b, c, d]}); const expected = ' -------------T---'; expectObservable(source.pipe(prioritizedGuardValue())).toBe( expected, resultLookup, /* an error here maybe */ ); }); }); it('should propagate errors', () => { testScheduler.run(({hot, cold, expectObservable}) => { const a = cold(' --(T|)', TF); const b = cold(' ------#', TF); const c = cold(' ----------(F|)', TF); const source = hot('---o------', {o: [a, b, c]}); const expected = ' ---------#'; expectObservable(source.pipe(prioritizedGuardValue())).toBe( expected, TF, /* an error here maybe */ ); }); }); }); function assertDeepEquals(a: any, b: any) { return expect(a).toEqual(b); }
{ "end_byte": 6441, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/router/test/operators/prioritized_guard_value.spec.ts" }
angular/packages/router/test/operators/resolve_data.spec.ts_0_6905
/** * @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.dev/license */ import {Component} from '@angular/core'; import {TestBed} from '@angular/core/testing'; import {provideRouter, Router} from '@angular/router'; import {RouterTestingHarness} from '@angular/router/testing'; import {EMPTY, interval, NEVER, of} from 'rxjs'; describe('resolveData operator', () => { it('should take only the first emitted value of every resolver', async () => { TestBed.configureTestingModule({ providers: [provideRouter([{path: '**', children: [], resolve: {e1: () => interval()}}])], }); await RouterTestingHarness.create('/'); expect(TestBed.inject(Router).routerState.root.firstChild?.snapshot.data).toEqual({e1: 0}); }); it('should cancel navigation if a resolver does not complete', async () => { TestBed.configureTestingModule({ providers: [provideRouter([{path: '**', children: [], resolve: {e1: () => EMPTY}}])], }); await RouterTestingHarness.create('/a'); expect(TestBed.inject(Router).url).toEqual('/'); }); it('should cancel navigation if 1 of 2 resolvers does not emit', async () => { TestBed.configureTestingModule({ providers: [ provideRouter([{path: '**', children: [], resolve: {e0: () => of(0), e1: () => EMPTY}}]), ], }); await RouterTestingHarness.create('/a'); expect(TestBed.inject(Router).url).toEqual('/'); }); it("should complete instantly if at least one resolver doesn't emit", async () => { TestBed.configureTestingModule({ providers: [ provideRouter([{path: '**', children: [], resolve: {e0: () => EMPTY, e1: () => NEVER}}]), ], }); await RouterTestingHarness.create('/a'); expect(TestBed.inject(Router).url).toEqual('/'); }); it('should run resolvers in different parts of the tree', async () => { let value = 0; let bValue = 0; TestBed.configureTestingModule({ providers: [ provideRouter([ { path: 'a', runGuardsAndResolvers: () => false, children: [ { path: '', resolve: {d0: () => ++value}, runGuardsAndResolvers: 'always', children: [], }, ], }, { path: 'b', outlet: 'aux', runGuardsAndResolvers: () => false, children: [ { path: '', resolve: {d1: () => ++bValue}, runGuardsAndResolvers: 'always', children: [], }, ], }, ]), ], }); const router = TestBed.inject(Router); const harness = await RouterTestingHarness.create('/a(aux:b)'); expect(router.routerState.root.children[0]?.firstChild?.snapshot.data).toEqual({d0: 1}); expect(router.routerState.root.children[1]?.firstChild?.snapshot.data).toEqual({d1: 1}); await harness.navigateByUrl('/a(aux:b)#new'); expect(router.routerState.root.children[0]?.firstChild?.snapshot.data).toEqual({d0: 2}); expect(router.routerState.root.children[1]?.firstChild?.snapshot.data).toEqual({d1: 2}); }); it('should update children inherited data when resolvers run', async () => { let value = 0; TestBed.configureTestingModule({ providers: [ provideRouter([ { path: 'a', children: [{path: 'b', children: []}], resolve: {d0: () => ++value}, runGuardsAndResolvers: 'always', }, ]), ], }); const harness = await RouterTestingHarness.create('/a/b'); expect(TestBed.inject(Router).routerState.root.firstChild?.snapshot.data).toEqual({d0: 1}); expect(TestBed.inject(Router).routerState.root.firstChild?.firstChild?.snapshot.data).toEqual({ d0: 1, }); await harness.navigateByUrl('/a/b#new'); expect(TestBed.inject(Router).routerState.root.firstChild?.snapshot.data).toEqual({d0: 2}); expect(TestBed.inject(Router).routerState.root.firstChild?.firstChild?.snapshot.data).toEqual({ d0: 2, }); }); it('should have correct data when parent resolver runs but data is not inherited', async () => { @Component({ template: '', standalone: false, }) class Empty {} TestBed.configureTestingModule({ providers: [ provideRouter([ { path: 'a', component: Empty, data: {parent: 'parent'}, resolve: {other: () => 'other'}, children: [ { path: 'b', data: {child: 'child'}, component: Empty, }, ], }, ]), ], }); await RouterTestingHarness.create('/a/b'); const rootSnapshot = TestBed.inject(Router).routerState.root.firstChild!.snapshot; expect(rootSnapshot.data).toEqual({parent: 'parent', other: 'other'}); expect(rootSnapshot.firstChild!.data).toEqual({child: 'child'}); }); it('should have static title when there is a resolver', async () => { @Component({ template: '', standalone: false, }) class Empty {} TestBed.configureTestingModule({ providers: [ provideRouter([ { path: 'a', title: 'a title', component: Empty, resolve: {other: () => 'other'}, children: [ { path: 'b', title: 'b title', component: Empty, resolve: {otherb: () => 'other b'}, }, ], }, ]), ], }); await RouterTestingHarness.create('/a/b'); const rootSnapshot = TestBed.inject(Router).routerState.root.firstChild!.snapshot; expect(rootSnapshot.title).toBe('a title'); expect(rootSnapshot.firstChild!.title).toBe('b title'); }); it('should inherit resolved data from parent of parent route', async () => { @Component({ template: '', standalone: false, }) class Empty {} TestBed.configureTestingModule({ providers: [ provideRouter([ { path: 'a', resolve: {aResolve: () => 'a'}, children: [ { path: 'b', resolve: {bResolve: () => 'b'}, children: [{path: 'c', component: Empty}], }, ], }, ]), ], }); await RouterTestingHarness.create('/a/b/c'); const rootSnapshot = TestBed.inject(Router).routerState.root.firstChild!.snapshot; expect(rootSnapshot.firstChild!.firstChild!.data).toEqual({bResolve: 'b', aResolve: 'a'}); }); });
{ "end_byte": 6905, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/router/test/operators/resolve_data.spec.ts" }
angular/packages/router/test/utils/tree.spec.ts_0_1886
/** * @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.dev/license */ import {Tree, TreeNode} from '../../src/utils/tree'; describe('tree', () => { it('should return the root of the tree', () => { const t = new Tree<any>(new TreeNode<number>(1, [])) as any; expect(t.root).toEqual(1); }); it('should return the parent of a node', () => { const t = new Tree<any>(new TreeNode<number>(1, [new TreeNode<number>(2, [])])) as any; expect(t.parent(1)).toEqual(null); expect(t.parent(2)).toEqual(1); }); it('should return the parent of a node (second child)', () => { const t = new Tree<any>( new TreeNode<number>(1, [new TreeNode<number>(2, []), new TreeNode<number>(3, [])]), ) as any; expect(t.parent(1)).toEqual(null); expect(t.parent(3)).toEqual(1); }); it('should return the children of a node', () => { const t = new Tree<any>(new TreeNode<number>(1, [new TreeNode<number>(2, [])])) as any; expect(t.children(1)).toEqual([2]); expect(t.children(2)).toEqual([]); }); it('should return the first child of a node', () => { const t = new Tree<any>(new TreeNode<number>(1, [new TreeNode<number>(2, [])])) as any; expect(t.firstChild(1)).toEqual(2); expect(t.firstChild(2)).toEqual(null); }); it('should return the siblings of a node', () => { const t = new Tree<any>( new TreeNode<number>(1, [new TreeNode<number>(2, []), new TreeNode<number>(3, [])]), ) as any; expect(t.siblings(2)).toEqual([3]); expect(t.siblings(1)).toEqual([]); }); it('should return the path to the root', () => { const t = new Tree<any>(new TreeNode<number>(1, [new TreeNode<number>(2, [])])) as any; expect(t.pathFromRoot(2)).toEqual([1, 2]); }); });
{ "end_byte": 1886, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/router/test/utils/tree.spec.ts" }
angular/packages/router/testing/PACKAGE.md_0_61
Supplies a testing module for the Angular `Router` subsystem.
{ "end_byte": 61, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/router/testing/PACKAGE.md" }
angular/packages/router/testing/BUILD.bazel_0_777
load("//tools:defaults.bzl", "generate_api_docs", "ng_module") package(default_visibility = ["//visibility:public"]) exports_files(["package.json"]) ng_module( name = "testing", srcs = glob(["**/*.ts"]), deps = [ "//packages/common", "//packages/common/testing", "//packages/core", "//packages/core/testing", "//packages/router", "@npm//rxjs", ], ) filegroup( name = "files_for_docgen", srcs = glob([ "*.ts", "src/**/*.ts", ]) + ["PACKAGE.md"], ) generate_api_docs( name = "router_testing_docs", srcs = [ ":files_for_docgen", "//packages:common_files_and_deps_for_docs", ], entry_point = ":index.ts", module_name = "@angular/router/testing", )
{ "end_byte": 777, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/router/testing/BUILD.bazel" }
angular/packages/router/testing/index.ts_0_481
/** * @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.dev/license */ // This file is not used to build this module. It is only used during editing // by the TypeScript language service and during build for verification. `ngc` // replaces this file with production index.ts when it rewrites private symbol // names. export * from './public_api';
{ "end_byte": 481, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/router/testing/index.ts" }
angular/packages/router/testing/public_api.ts_0_398
/** * @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.dev/license */ /** * @module * @description * Entry point for all public APIs of this package. */ export * from './src/testing'; // This file only reexports content of the `src` folder. Keep it that way.
{ "end_byte": 398, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/router/testing/public_api.ts" }
angular/packages/router/testing/test/BUILD.bazel_0_882
load("//tools:defaults.bzl", "jasmine_node_test", "karma_web_test_suite", "ts_library") ts_library( name = "test_lib", testonly = True, srcs = glob(["**/*.ts"]), # Visible to //:saucelabs_unit_tests_poc target visibility = ["//:__pkg__"], deps = [ "//packages/common", "//packages/common/testing", "//packages/core", "//packages/core/testing", "//packages/platform-browser", "//packages/platform-browser-dynamic", "//packages/platform-browser/testing", "//packages/private/testing", "//packages/router", "//packages/router/testing", "@npm//rxjs", ], ) jasmine_node_test( name = "test", bootstrap = ["//tools/testing:node"], deps = [ ":test_lib", ], ) karma_web_test_suite( name = "test_web", deps = [ ":test_lib", ], )
{ "end_byte": 882, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/router/testing/test/BUILD.bazel" }
angular/packages/router/testing/test/router_testing_harness.spec.ts_0_4975
/** * @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.dev/license */ import {AsyncPipe} from '@angular/common'; import {Component, inject} from '@angular/core'; import {TestBed} from '@angular/core/testing'; import {ActivatedRoute, provideRouter, Router} from '@angular/router'; import {RouterTestingHarness} from '@angular/router/testing'; import {of} from 'rxjs'; import {delay} from 'rxjs/operators'; import {withRouterConfig} from '../../src/provide_router'; describe('navigateForTest', () => { it('gives null for the activatedComponent when no routes are configured', async () => { TestBed.configureTestingModule({providers: [provideRouter([])]}); const harness = await RouterTestingHarness.create('/'); expect(harness.routeDebugElement).toBeNull(); }); it('navigates to routed component', async () => { @Component({standalone: true, template: 'hello {{name}}'}) class TestCmp { name = 'world'; } TestBed.configureTestingModule({providers: [provideRouter([{path: '', component: TestCmp}])]}); const harness = await RouterTestingHarness.create(); const activatedComponent = await harness.navigateByUrl('/', TestCmp); expect(activatedComponent).toBeInstanceOf(TestCmp); expect(harness.routeNativeElement?.innerHTML).toContain('hello world'); }); it('executes guards on the path', async () => { let guardCalled = false; TestBed.configureTestingModule({ providers: [ provideRouter([ { path: '', canActivate: [ () => { guardCalled = true; return true; }, ], children: [], }, ]), ], }); await RouterTestingHarness.create('/'); expect(guardCalled).toBeTrue(); }); it('throws error if routing throws', async () => { TestBed.configureTestingModule({ providers: [ provideRouter( [ { path: 'e', canActivate: [ () => { throw new Error('oh no'); }, ], children: [], }, ], withRouterConfig({resolveNavigationPromiseOnError: true}), ), ], }); const harness = await RouterTestingHarness.create(); await expectAsync(harness.navigateByUrl('e')).toBeResolvedTo(null); }); it('can observe param changes on routed component with second navigation', async () => { @Component({standalone: true, template: '{{(route.params | async)?.id}}', imports: [AsyncPipe]}) class TestCmp { constructor(readonly route: ActivatedRoute) {} } TestBed.configureTestingModule({ providers: [provideRouter([{path: ':id', component: TestCmp}])], }); const harness = await RouterTestingHarness.create(); const activatedComponent = await harness.navigateByUrl('/123', TestCmp); expect(activatedComponent.route).toBeInstanceOf(ActivatedRoute); expect(harness.routeNativeElement?.innerHTML).toContain('123'); await harness.navigateByUrl('/456'); expect(harness.routeNativeElement?.innerHTML).toContain('456'); }); it('throws an error if the routed component instance does not match the one required', async () => { @Component({standalone: true, template: ''}) class TestCmp {} @Component({standalone: true, template: ''}) class OtherCmp {} TestBed.configureTestingModule({ providers: [provideRouter([{path: '**', component: TestCmp}])], }); const harness = await RouterTestingHarness.create(); await expectAsync(harness.navigateByUrl('/123', OtherCmp)).toBeRejected(); }); it('throws an error if navigation fails but expected a component instance', async () => { @Component({standalone: true, template: ''}) class TestCmp {} TestBed.configureTestingModule({ providers: [provideRouter([{path: '**', canActivate: [() => false], component: TestCmp}])], }); const harness = await RouterTestingHarness.create(); await expectAsync(harness.navigateByUrl('/123', TestCmp)).toBeRejected(); }); it('waits for redirects using router.navigate', async () => { @Component({standalone: true, template: 'test'}) class TestCmp {} @Component({standalone: true, template: 'redirect'}) class OtherCmp {} TestBed.configureTestingModule({ providers: [ provideRouter([ { path: 'test', canActivate: [() => inject(Router).navigateByUrl('/redirect')], component: TestCmp, }, {path: 'redirect', canActivate: [() => of(true).pipe(delay(100))], component: OtherCmp}, ]), ], }); await RouterTestingHarness.create('test'); expect(TestBed.inject(Router).url).toEqual('/redirect'); }); });
{ "end_byte": 4975, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/router/testing/test/router_testing_harness.spec.ts" }
angular/packages/router/testing/src/testing.ts_0_409
/** * @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.dev/license */ /** * @module * @description * Entry point for all public APIs of the router/testing package. */ export * from './router_testing_module'; export {RouterTestingHarness} from './router_testing_harness';
{ "end_byte": 409, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/router/testing/src/testing.ts" }
angular/packages/router/testing/src/router_testing_harness.ts_0_6734
/** * @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.dev/license */ import { Component, DebugElement, Injectable, Type, ViewChild, WritableSignal, signal, } from '@angular/core'; import {ComponentFixture, TestBed} from '@angular/core/testing'; import {Router, RouterOutlet, ɵafterNextNavigation as afterNextNavigation} from '@angular/router'; @Injectable({providedIn: 'root'}) export class RootFixtureService { private fixture?: ComponentFixture<RootCmp>; private harness?: RouterTestingHarness; createHarness(): RouterTestingHarness { if (this.harness) { throw new Error('Only one harness should be created per test.'); } this.harness = new RouterTestingHarness(this.getRootFixture()); return this.harness; } private getRootFixture(): ComponentFixture<RootCmp> { if (this.fixture !== undefined) { return this.fixture; } this.fixture = TestBed.createComponent(RootCmp); this.fixture.detectChanges(); return this.fixture; } } @Component({ standalone: true, template: '<router-outlet [routerOutletData]="routerOutletData()"></router-outlet>', imports: [RouterOutlet], }) export class RootCmp { @ViewChild(RouterOutlet) outlet?: RouterOutlet; readonly routerOutletData = signal<unknown>(undefined); } /** * A testing harness for the `Router` to reduce the boilerplate needed to test routes and routed * components. * * @publicApi */ export class RouterTestingHarness { /** * Creates a `RouterTestingHarness` instance. * * The `RouterTestingHarness` also creates its own root component with a `RouterOutlet` for the * purposes of rendering route components. * * Throws an error if an instance has already been created. * Use of this harness also requires `destroyAfterEach: true` in the `ModuleTeardownOptions` * * @param initialUrl The target of navigation to trigger before returning the harness. */ static async create(initialUrl?: string): Promise<RouterTestingHarness> { const harness = TestBed.inject(RootFixtureService).createHarness(); if (initialUrl !== undefined) { await harness.navigateByUrl(initialUrl); } return harness; } /** * Fixture of the root component of the RouterTestingHarness */ public readonly fixture: ComponentFixture<{routerOutletData: WritableSignal<unknown>}>; /** @internal */ constructor(fixture: ComponentFixture<{routerOutletData: WritableSignal<unknown>}>) { this.fixture = fixture; } /** Instructs the root fixture to run change detection. */ detectChanges(): void { this.fixture.detectChanges(); } /** The `DebugElement` of the `RouterOutlet` component. `null` if the outlet is not activated. */ get routeDebugElement(): DebugElement | null { const outlet = (this.fixture.componentInstance as RootCmp).outlet; if (!outlet || !outlet.isActivated) { return null; } return this.fixture.debugElement.query((v) => v.componentInstance === outlet.component); } /** The native element of the `RouterOutlet` component. `null` if the outlet is not activated. */ get routeNativeElement(): HTMLElement | null { return this.routeDebugElement?.nativeElement ?? null; } /** * Triggers a `Router` navigation and waits for it to complete. * * The root component with a `RouterOutlet` created for the harness is used to render `Route` * components. The root component is reused within the same test in subsequent calls to * `navigateForTest`. * * When testing `Routes` with a guards that reject the navigation, the `RouterOutlet` might not be * activated and the `activatedComponent` may be `null`. * * {@example router/testing/test/router_testing_harness_examples.spec.ts region='Guard'} * * @param url The target of the navigation. Passed to `Router.navigateByUrl`. * @returns The activated component instance of the `RouterOutlet` after navigation completes * (`null` if the outlet does not get activated). */ async navigateByUrl(url: string): Promise<null | {}>; /** * Triggers a router navigation and waits for it to complete. * * The root component with a `RouterOutlet` created for the harness is used to render `Route` * components. * * {@example router/testing/test/router_testing_harness_examples.spec.ts region='RoutedComponent'} * * The root component is reused within the same test in subsequent calls to `navigateByUrl`. * * This function also makes it easier to test components that depend on `ActivatedRoute` data. * * {@example router/testing/test/router_testing_harness_examples.spec.ts region='ActivatedRoute'} * * @param url The target of the navigation. Passed to `Router.navigateByUrl`. * @param requiredRoutedComponentType After navigation completes, the required type for the * activated component of the `RouterOutlet`. If the outlet is not activated or a different * component is activated, this function will throw an error. * @returns The activated component instance of the `RouterOutlet` after navigation completes. */ async navigateByUrl<T>(url: string, requiredRoutedComponentType: Type<T>): Promise<T>; async navigateByUrl<T>(url: string, requiredRoutedComponentType?: Type<T>): Promise<T | null> { const router = TestBed.inject(Router); let resolveFn!: () => void; const redirectTrackingPromise = new Promise<void>((resolve) => { resolveFn = resolve; }); afterNextNavigation(TestBed.inject(Router), resolveFn); await router.navigateByUrl(url); await redirectTrackingPromise; this.fixture.detectChanges(); const outlet = (this.fixture.componentInstance as RootCmp).outlet; // The outlet might not be activated if the user is testing a navigation for a guard that // rejects if (outlet && outlet.isActivated && outlet.activatedRoute.component) { const activatedComponent = outlet.component; if ( requiredRoutedComponentType !== undefined && !(activatedComponent instanceof requiredRoutedComponentType) ) { throw new Error( `Unexpected routed component type. Expected ${requiredRoutedComponentType.name} but got ${activatedComponent.constructor.name}`, ); } return activatedComponent as T; } else { if (requiredRoutedComponentType !== undefined) { throw new Error( `Unexpected routed component type. Expected ${requiredRoutedComponentType.name} but the navigation did not activate any component.`, ); } return null; } } }
{ "end_byte": 6734, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/router/testing/src/router_testing_harness.ts" }
angular/packages/router/testing/src/router_testing_module.ts_0_2737
/** * @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.dev/license */ import {Location} from '@angular/common'; import {provideLocationMocks} from '@angular/common/testing'; import {Compiler, inject, Injector, ModuleWithProviders, NgModule} from '@angular/core'; import { ChildrenOutletContexts, ExtraOptions, NoPreloading, Route, Router, ROUTER_CONFIGURATION, RouteReuseStrategy, RouterModule, ROUTES, Routes, TitleStrategy, UrlHandlingStrategy, UrlSerializer, withPreloading, ɵROUTER_PROVIDERS as ROUTER_PROVIDERS, } from '@angular/router'; function isUrlHandlingStrategy( opts: ExtraOptions | UrlHandlingStrategy, ): opts is UrlHandlingStrategy { // This property check is needed because UrlHandlingStrategy is an interface and doesn't exist at // runtime. return 'shouldProcessUrl' in opts; } function throwInvalidConfigError(parameter: string): never { throw new Error( `Parameter ${parameter} does not match the one available in the injector. ` + '`setupTestingRouter` is meant to be used as a factory function with dependencies coming from DI.', ); } /** * @description * * Sets up the router to be used for testing. * * The modules sets up the router to be used for testing. * It provides spy implementations of `Location` and `LocationStrategy`. * * @usageNotes * ### Example * * ``` * beforeEach(() => { * TestBed.configureTestingModule({ * imports: [ * RouterModule.forRoot( * [{path: '', component: BlankCmp}, {path: 'simple', component: SimpleCmp}] * ) * ] * }); * }); * ``` * * @publicApi * @deprecated Use `provideRouter` or `RouterModule`/`RouterModule.forRoot` instead. * This module was previously used to provide a helpful collection of test fakes, * most notably those for `Location` and `LocationStrategy`. These are generally not * required anymore, as `MockPlatformLocation` is provided in `TestBed` by default. * However, you can use them directly with `provideLocationMocks`. */ @NgModule({ exports: [RouterModule], providers: [ ROUTER_PROVIDERS, provideLocationMocks(), withPreloading(NoPreloading).ɵproviders, {provide: ROUTES, multi: true, useValue: []}, ], }) export class RouterTestingModule { static withRoutes( routes: Routes, config?: ExtraOptions, ): ModuleWithProviders<RouterTestingModule> { return { ngModule: RouterTestingModule, providers: [ {provide: ROUTES, multi: true, useValue: routes}, {provide: ROUTER_CONFIGURATION, useValue: config ? config : {}}, ], }; } }
{ "end_byte": 2737, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/router/testing/src/router_testing_module.ts" }
angular/packages/router/scripts/karma.sh_0_58
#!/usr/bin/env bash ../../../node_modules/.bin/karma start
{ "end_byte": 58, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/router/scripts/karma.sh" }
angular/packages/router/scripts/build.sh_0_73
#!/usr/bin/env bash set -e -o pipefail ../../../node_modules/.bin/tsc -w
{ "end_byte": 73, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/router/scripts/build.sh" }
angular/packages/router/src/router_config.ts_0_7415
/** * @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.dev/license */ import {InjectionToken} from '@angular/core'; import {OnSameUrlNavigation, QueryParamsHandling, RedirectCommand} from './models'; /** * Allowed values in an `ExtraOptions` object that configure * when the router performs the initial navigation operation. * * * 'enabledNonBlocking' - (default) The initial navigation starts after the * root component has been created. The bootstrap is not blocked on the completion of the initial * navigation. * * 'enabledBlocking' - The initial navigation starts before the root component is created. * The bootstrap is blocked until the initial navigation is complete. This value should be set in * case you use [server-side rendering](guide/ssr), but do not enable [hydration](guide/hydration) * for your application. * * 'disabled' - The initial navigation is not performed. The location listener is set up before * the root component gets created. Use if there is a reason to have * more control over when the router starts its initial navigation due to some complex * initialization logic. * * @see {@link forRoot()} * * @publicApi */ export type InitialNavigation = 'disabled' | 'enabledBlocking' | 'enabledNonBlocking'; /** * Extra configuration options that can be used with the `withRouterConfig` function. * * @publicApi */ export interface RouterConfigOptions { /** * 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. This means that if the URL of the browser is updated * _before_ the navigation is canceled, the Router will simply replace the item in history rather * than trying to restore to the previous location in the session history. This happens most * frequently with `urlUpdateStrategy: 'eager'` and navigations with the browser back/forward * buttons. * * 'computed' - Will attempt to return to the same index in the session history that corresponds * to the Angular route when the navigation gets cancelled. For example, if the browser back * button is clicked and the navigation is cancelled, the Router will trigger a forward navigation * and vice versa. * * Note: the 'computed' option is incompatible with any `UrlHandlingStrategy` which only * handles a portion of the URL because the history restoration navigates to the previous place in * the browser history rather than simply resetting a portion of the URL. * * The default value is `replace` when not set. */ canceledNavigationResolution?: 'replace' | 'computed'; /** * Configures the default for handling a navigation request to the current URL. * * If unset, the `Router` will use `'ignore'`. * * @see {@link OnSameUrlNavigation} */ onSameUrlNavigation?: OnSameUrlNavigation; /** * Defines how the router merges parameters, data, and resolved data from parent to child * routes. * * By default ('emptyOnly'), a route inherits the parent route's parameters when the route itself * has an empty path (meaning its configured with path: '') or when the parent route doesn't have * any component set. * * Set to 'always' to enable unconditional inheritance of parent parameters. * * Note that when dealing with matrix parameters, "parent" refers to the parent `Route` * config which does not necessarily mean the "URL segment to the left". When the `Route` `path` * contains multiple segments, the matrix parameters must appear on the last segment. For example, * matrix parameters for `{path: 'a/b', component: MyComp}` should appear as `a/b;foo=bar` and not * `a;foo=bar/b`. * */ paramsInheritanceStrategy?: 'emptyOnly' | 'always'; /** * Defines when the router updates the browser URL. By default ('deferred'), * update after successful navigation. * Set to 'eager' if prefer to update the URL at the beginning of navigation. * Updating the URL early allows you to handle a failure of navigation by * showing an error message with the URL that failed. */ urlUpdateStrategy?: 'deferred' | 'eager'; /** * The default strategy to use for handling query params in `Router.createUrlTree` when one is not provided. * * The `createUrlTree` method is used internally by `Router.navigate` and `RouterLink`. * Note that `QueryParamsHandling` does not apply to `Router.navigateByUrl`. * * When neither the default nor the queryParamsHandling option is specified in the call to `createUrlTree`, * the current parameters will be replaced by new parameters. * * @see {@link Router#createUrlTree} * @see {@link QueryParamsHandling} */ defaultQueryParamsHandling?: QueryParamsHandling; /** * When `true`, the `Promise` will instead resolve with `false`, as it does with other failed * navigations (for example, when guards are rejected). * Otherwise the `Promise` returned by the Router's navigation with be rejected * if an error occurs. */ resolveNavigationPromiseOnError?: boolean; } /** * Configuration options for the scrolling feature which can be used with `withInMemoryScrolling` * function. * * @publicApi */ export interface InMemoryScrollingOptions { /** * When set to 'enabled', scrolls to the anchor element when the URL has a fragment. * Anchor scrolling is disabled by default. * * Anchor scrolling does not happen on 'popstate'. Instead, we restore the position * that we stored or scroll to the top. */ anchorScrolling?: 'disabled' | 'enabled'; /** * Configures if the scroll position needs to be restored when navigating back. * * * 'disabled'- (Default) Does nothing. Scroll position is maintained on navigation. * * 'top'- Sets the scroll position to x = 0, y = 0 on all navigation. * * 'enabled'- Restores the previous scroll position on backward navigation, else sets the * position to the anchor if one is provided, or sets the scroll position to [0, 0] (forward * navigation). This option will be the default in the future. * * You can implement custom scroll restoration behavior by adapting the enabled behavior as * in the following example. * * ```typescript * class AppComponent { * movieData: any; * * constructor(private router: Router, private viewportScroller: ViewportScroller, * changeDetectorRef: ChangeDetectorRef) { * router.events.pipe(filter((event: Event): event is Scroll => event instanceof Scroll) * ).subscribe(e => { * fetch('http://example.com/movies.json').then(response => { * this.movieData = response.json(); * // update the template with the data before restoring scroll * changeDetectorRef.detectChanges(); * * if (e.position) { * viewportScroller.scrollToPosition(e.position); * } * }); * }); * } * } * ``` */ scrollPositionRestoration?: 'disabled' | 'enabled' | 'top'; } /** * A set of configuration options for a router module, provided in the * `forRoot()` method. * * @see {@link forRoot()} * * * @publicApi */
{ "end_byte": 7415, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/router/src/router_config.ts" }
angular/packages/router/src/router_config.ts_7416_10427
export interface ExtraOptions extends InMemoryScrollingOptions, RouterConfigOptions { /** * When true, log all internal navigation events to the console. * Use for debugging. */ enableTracing?: boolean; /** * When true, enable the location strategy that uses the URL fragment * instead of the history API. */ useHash?: boolean; /** * One of `enabled`, `enabledBlocking`, `enabledNonBlocking` or `disabled`. * When set to `enabled` or `enabledBlocking`, the initial navigation starts before the root * component is created. The bootstrap is blocked until the initial navigation is complete. This * value should be set in case you use [server-side rendering](guide/ssr), but do not enable * [hydration](guide/hydration) for your application. When set to `enabledNonBlocking`, * the initial navigation starts after the root component has been created. * The bootstrap is not blocked on the completion of the initial navigation. When set to * `disabled`, the initial navigation is not performed. The location listener is set up before the * root component gets created. Use if there is a reason to have more control over when the router * starts its initial navigation due to some complex initialization logic. */ initialNavigation?: InitialNavigation; /** * When true, enables binding information from the `Router` state directly to the inputs of the * component in `Route` configurations. */ bindToComponentInputs?: boolean; /** * When true, enables view transitions in the Router by running the route activation and * deactivation inside of `document.startViewTransition`. * * @see https://developer.chrome.com/docs/web-platform/view-transitions/ * @see https://developer.mozilla.org/en-US/docs/Web/API/View_Transitions_API * @experimental */ enableViewTransitions?: boolean; /** * A custom error handler for failed navigations. * 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. * * @see RouterConfigOptions */ errorHandler?: (error: any) => RedirectCommand | any; /** * Configures a preloading strategy. * One of `PreloadAllModules` or `NoPreloading` (the default). */ preloadingStrategy?: any; /** * Configures the scroll offset the router will use when scrolling to an element. * * When given a tuple with x and y position value, * the router uses that offset each time it scrolls. * When given a function, the router invokes the function every time * it restores scroll position. */ scrollOffset?: [number, number] | (() => [number, number]); } /** * A DI token for the router service. * * @publicApi */ export const ROUTER_CONFIGURATION = new InjectionToken<ExtraOptions>( typeof ngDevMode === 'undefined' || ngDevMode ? 'router config' : '', { providedIn: 'root', factory: () => ({}), }, );
{ "end_byte": 10427, "start_byte": 7416, "url": "https://github.com/angular/angular/blob/main/packages/router/src/router_config.ts" }
angular/packages/router/src/models_deprecated.ts_0_462
/** * @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.dev/license */ // This file contains re-exports of deprecated interfaces in `models.ts` // The public API re-exports everything from this file, which can be patched // locally in g3 to prevent regressions after cleanups complete. export {DeprecatedGuard} from './models';
{ "end_byte": 462, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/router/src/models_deprecated.ts" }
angular/packages/router/src/create_url_tree.ts_0_8027
/** * @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.dev/license */ import {ɵRuntimeError as RuntimeError} from '@angular/core'; import {RuntimeErrorCode} from './errors'; import {ActivatedRouteSnapshot} from './router_state'; import {Params, PRIMARY_OUTLET} from './shared'; import {createRoot, squashSegmentGroup, UrlSegment, UrlSegmentGroup, UrlTree} from './url_tree'; import {last, shallowEqual} from './utils/collection'; /** * Creates a `UrlTree` relative to an `ActivatedRouteSnapshot`. * * @publicApi * * * @param relativeTo The `ActivatedRouteSnapshot` to apply the commands to * @param commands An array of URL fragments with which to construct the new URL tree. * If the path is static, can be the literal URL string. For a dynamic path, pass an array of path * segments, followed by the parameters for each segment. * The fragments are applied to the one provided in the `relativeTo` parameter. * @param queryParams The query parameters for the `UrlTree`. `null` if the `UrlTree` does not have * any query parameters. * @param fragment The fragment for the `UrlTree`. `null` if the `UrlTree` does not have a fragment. * * @usageNotes * * ``` * // create /team/33/user/11 * createUrlTreeFromSnapshot(snapshot, ['/team', 33, 'user', 11]); * * // create /team/33;expand=true/user/11 * createUrlTreeFromSnapshot(snapshot, ['/team', 33, {expand: true}, 'user', 11]); * * // you can collapse static segments like this (this works only with the first passed-in value): * createUrlTreeFromSnapshot(snapshot, ['/team/33/user', userId]); * * // If the first segment can contain slashes, and you do not want the router to split it, * // you can do the following: * createUrlTreeFromSnapshot(snapshot, [{segmentPath: '/one/two'}]); * * // create /team/33/(user/11//right:chat) * createUrlTreeFromSnapshot(snapshot, ['/team', 33, {outlets: {primary: 'user/11', right: * 'chat'}}], null, null); * * // remove the right secondary node * createUrlTreeFromSnapshot(snapshot, ['/team', 33, {outlets: {primary: 'user/11', right: null}}]); * * // For the examples below, assume the current URL is for the `/team/33/user/11` and the * `ActivatedRouteSnapshot` points to `user/11`: * * // navigate to /team/33/user/11/details * createUrlTreeFromSnapshot(snapshot, ['details']); * * // navigate to /team/33/user/22 * createUrlTreeFromSnapshot(snapshot, ['../22']); * * // navigate to /team/44/user/22 * createUrlTreeFromSnapshot(snapshot, ['../../team/44/user/22']); * ``` */ export function createUrlTreeFromSnapshot( relativeTo: ActivatedRouteSnapshot, commands: any[], queryParams: Params | null = null, fragment: string | null = null, ): UrlTree { const relativeToUrlSegmentGroup = createSegmentGroupFromRoute(relativeTo); return createUrlTreeFromSegmentGroup(relativeToUrlSegmentGroup, commands, queryParams, fragment); } export function createSegmentGroupFromRoute(route: ActivatedRouteSnapshot): UrlSegmentGroup { let targetGroup: UrlSegmentGroup | undefined; function createSegmentGroupFromRouteRecursive( currentRoute: ActivatedRouteSnapshot, ): UrlSegmentGroup { const childOutlets: {[outlet: string]: UrlSegmentGroup} = {}; for (const childSnapshot of currentRoute.children) { const root = createSegmentGroupFromRouteRecursive(childSnapshot); childOutlets[childSnapshot.outlet] = root; } const segmentGroup = new UrlSegmentGroup(currentRoute.url, childOutlets); if (currentRoute === route) { targetGroup = segmentGroup; } return segmentGroup; } const rootCandidate = createSegmentGroupFromRouteRecursive(route.root); const rootSegmentGroup = createRoot(rootCandidate); return targetGroup ?? rootSegmentGroup; } export function createUrlTreeFromSegmentGroup( relativeTo: UrlSegmentGroup, commands: any[], queryParams: Params | null, fragment: string | null, ): UrlTree { let root = relativeTo; while (root.parent) { root = root.parent; } // There are no commands so the `UrlTree` goes to the same path as the one created from the // `UrlSegmentGroup`. All we need to do is update the `queryParams` and `fragment` without // applying any other logic. if (commands.length === 0) { return tree(root, root, root, queryParams, fragment); } const nav = computeNavigation(commands); if (nav.toRoot()) { return tree(root, root, new UrlSegmentGroup([], {}), queryParams, fragment); } const position = findStartingPositionForTargetGroup(nav, root, relativeTo); const newSegmentGroup = position.processChildren ? updateSegmentGroupChildren(position.segmentGroup, position.index, nav.commands) : updateSegmentGroup(position.segmentGroup, position.index, nav.commands); return tree(root, position.segmentGroup, newSegmentGroup, queryParams, fragment); } function isMatrixParams(command: any): boolean { return typeof command === 'object' && command != null && !command.outlets && !command.segmentPath; } /** * Determines if a given command has an `outlets` map. When we encounter a command * with an outlets k/v map, we need to apply each outlet individually to the existing segment. */ function isCommandWithOutlets(command: any): command is {outlets: {[key: string]: any}} { return typeof command === 'object' && command != null && command.outlets; } function tree( oldRoot: UrlSegmentGroup, oldSegmentGroup: UrlSegmentGroup, newSegmentGroup: UrlSegmentGroup, queryParams: Params | null, fragment: string | null, ): UrlTree { let qp: any = {}; if (queryParams) { Object.entries(queryParams).forEach(([name, value]) => { qp[name] = Array.isArray(value) ? value.map((v: any) => `${v}`) : `${value}`; }); } let rootCandidate: UrlSegmentGroup; if (oldRoot === oldSegmentGroup) { rootCandidate = newSegmentGroup; } else { rootCandidate = replaceSegment(oldRoot, oldSegmentGroup, newSegmentGroup); } const newRoot = createRoot(squashSegmentGroup(rootCandidate)); return new UrlTree(newRoot, qp, fragment); } /** * Replaces the `oldSegment` which is located in some child of the `current` with the `newSegment`. * This also has the effect of creating new `UrlSegmentGroup` copies to update references. This * shouldn't be necessary but the fallback logic for an invalid ActivatedRoute in the creation uses * the Router's current url tree. If we don't create new segment groups, we end up modifying that * value. */ function replaceSegment( current: UrlSegmentGroup, oldSegment: UrlSegmentGroup, newSegment: UrlSegmentGroup, ): UrlSegmentGroup { const children: {[key: string]: UrlSegmentGroup} = {}; Object.entries(current.children).forEach(([outletName, c]) => { if (c === oldSegment) { children[outletName] = newSegment; } else { children[outletName] = replaceSegment(c, oldSegment, newSegment); } }); return new UrlSegmentGroup(current.segments, children); } class Navigation { constructor( public isAbsolute: boolean, public numberOfDoubleDots: number, public commands: any[], ) { if (isAbsolute && commands.length > 0 && isMatrixParams(commands[0])) { throw new RuntimeError( RuntimeErrorCode.ROOT_SEGMENT_MATRIX_PARAMS, (typeof ngDevMode === 'undefined' || ngDevMode) && 'Root segment cannot have matrix parameters', ); } const cmdWithOutlet = commands.find(isCommandWithOutlets); if (cmdWithOutlet && cmdWithOutlet !== last(commands)) { throw new RuntimeError( RuntimeErrorCode.MISPLACED_OUTLETS_COMMAND, (typeof ngDevMode === 'undefined' || ngDevMode) && '{outlets:{}} has to be the last command', ); } } public toRoot(): boolean { return this.isAbsolute && this.commands.length === 1 && this.commands[0] == '/'; } } /** Transforms commands to a normalized `Navigation` */
{ "end_byte": 8027, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/router/src/create_url_tree.ts" }
angular/packages/router/src/create_url_tree.ts_8028_15295
unction computeNavigation(commands: any[]): Navigation { if (typeof commands[0] === 'string' && commands.length === 1 && commands[0] === '/') { return new Navigation(true, 0, commands); } let numberOfDoubleDots = 0; let isAbsolute = false; const res: any[] = commands.reduce((res, cmd, cmdIdx) => { if (typeof cmd === 'object' && cmd != null) { if (cmd.outlets) { const outlets: {[k: string]: any} = {}; Object.entries(cmd.outlets).forEach(([name, commands]) => { outlets[name] = typeof commands === 'string' ? commands.split('/') : commands; }); return [...res, {outlets}]; } if (cmd.segmentPath) { return [...res, cmd.segmentPath]; } } if (!(typeof cmd === 'string')) { return [...res, cmd]; } if (cmdIdx === 0) { cmd.split('/').forEach((urlPart, partIndex) => { if (partIndex == 0 && urlPart === '.') { // skip './a' } else if (partIndex == 0 && urlPart === '') { // '/a' isAbsolute = true; } else if (urlPart === '..') { // '../a' numberOfDoubleDots++; } else if (urlPart != '') { res.push(urlPart); } }); return res; } return [...res, cmd]; }, []); return new Navigation(isAbsolute, numberOfDoubleDots, res); } class Position { constructor( public segmentGroup: UrlSegmentGroup, public processChildren: boolean, public index: number, ) {} } function findStartingPositionForTargetGroup( nav: Navigation, root: UrlSegmentGroup, target: UrlSegmentGroup, ): Position { if (nav.isAbsolute) { return new Position(root, true, 0); } if (!target) { // `NaN` is used only to maintain backwards compatibility with incorrectly mocked // `ActivatedRouteSnapshot` in tests. In prior versions of this code, the position here was // determined based on an internal property that was rarely mocked, resulting in `NaN`. In // reality, this code path should _never_ be touched since `target` is not allowed to be falsey. return new Position(root, false, NaN); } if (target.parent === null) { return new Position(target, true, 0); } const modifier = isMatrixParams(nav.commands[0]) ? 0 : 1; const index = target.segments.length - 1 + modifier; return createPositionApplyingDoubleDots(target, index, nav.numberOfDoubleDots); } function createPositionApplyingDoubleDots( group: UrlSegmentGroup, index: number, numberOfDoubleDots: number, ): Position { let g = group; let ci = index; let dd = numberOfDoubleDots; while (dd > ci) { dd -= ci; g = g.parent!; if (!g) { throw new RuntimeError( RuntimeErrorCode.INVALID_DOUBLE_DOTS, (typeof ngDevMode === 'undefined' || ngDevMode) && "Invalid number of '../'", ); } ci = g.segments.length; } return new Position(g, false, ci - dd); } function getOutlets(commands: unknown[]): {[k: string]: unknown[] | string} { if (isCommandWithOutlets(commands[0])) { return commands[0].outlets; } return {[PRIMARY_OUTLET]: commands}; } function updateSegmentGroup( segmentGroup: UrlSegmentGroup | undefined, startIndex: number, commands: any[], ): UrlSegmentGroup { segmentGroup ??= new UrlSegmentGroup([], {}); if (segmentGroup.segments.length === 0 && segmentGroup.hasChildren()) { return updateSegmentGroupChildren(segmentGroup, startIndex, commands); } const m = prefixedWith(segmentGroup, startIndex, commands); const slicedCommands = commands.slice(m.commandIndex); if (m.match && m.pathIndex < segmentGroup.segments.length) { const g = new UrlSegmentGroup(segmentGroup.segments.slice(0, m.pathIndex), {}); g.children[PRIMARY_OUTLET] = new UrlSegmentGroup( segmentGroup.segments.slice(m.pathIndex), segmentGroup.children, ); return updateSegmentGroupChildren(g, 0, slicedCommands); } else if (m.match && slicedCommands.length === 0) { return new UrlSegmentGroup(segmentGroup.segments, {}); } else if (m.match && !segmentGroup.hasChildren()) { return createNewSegmentGroup(segmentGroup, startIndex, commands); } else if (m.match) { return updateSegmentGroupChildren(segmentGroup, 0, slicedCommands); } else { return createNewSegmentGroup(segmentGroup, startIndex, commands); } } function updateSegmentGroupChildren( segmentGroup: UrlSegmentGroup, startIndex: number, commands: any[], ): UrlSegmentGroup { if (commands.length === 0) { return new UrlSegmentGroup(segmentGroup.segments, {}); } else { const outlets = getOutlets(commands); const children: {[key: string]: UrlSegmentGroup} = {}; // If the set of commands applies to anything other than the primary outlet and the child // segment is an empty path primary segment on its own, we want to apply the commands to the // empty child path rather than here. The outcome is that the empty primary child is effectively // removed from the final output UrlTree. Imagine the following config: // // {path: '', children: [{path: '**', outlet: 'popup'}]}. // // Navigation to /(popup:a) will activate the child outlet correctly Given a follow-up // navigation with commands // ['/', {outlets: {'popup': 'b'}}], we _would not_ want to apply the outlet commands to the // root segment because that would result in // //(popup:a)(popup:b) since the outlet command got applied one level above where it appears in // the `ActivatedRoute` rather than updating the existing one. // // Because empty paths do not appear in the URL segments and the fact that the segments used in // the output `UrlTree` are squashed to eliminate these empty paths where possible // https://github.com/angular/angular/blob/13f10de40e25c6900ca55bd83b36bd533dacfa9e/packages/router/src/url_tree.ts#L755 // it can be hard to determine what is the right thing to do when applying commands to a // `UrlSegmentGroup` that is created from an "unsquashed"/expanded `ActivatedRoute` tree. // This code effectively "squashes" empty path primary routes when they have no siblings on // the same level of the tree. if ( Object.keys(outlets).some((o) => o !== PRIMARY_OUTLET) && segmentGroup.children[PRIMARY_OUTLET] && segmentGroup.numberOfChildren === 1 && segmentGroup.children[PRIMARY_OUTLET].segments.length === 0 ) { const childrenOfEmptyChild = updateSegmentGroupChildren( segmentGroup.children[PRIMARY_OUTLET], startIndex, commands, ); return new UrlSegmentGroup(segmentGroup.segments, childrenOfEmptyChild.children); } Object.entries(outlets).forEach(([outlet, commands]) => { if (typeof commands === 'string') { commands = [commands]; } if (commands !== null) { children[outlet] = updateSegmentGroup(segmentGroup.children[outlet], startIndex, commands); } }); Object.entries(segmentGroup.children).forEach(([childOutlet, child]) => { if (outlets[childOutlet] === undefined) { children[childOutlet] = child; } }); return new UrlSegmentGroup(segmentGroup.segments, children); } }
{ "end_byte": 15295, "start_byte": 8028, "url": "https://github.com/angular/angular/blob/main/packages/router/src/create_url_tree.ts" }
angular/packages/router/src/create_url_tree.ts_15297_18612
unction prefixedWith(segmentGroup: UrlSegmentGroup, startIndex: number, commands: any[]) { let currentCommandIndex = 0; let currentPathIndex = startIndex; const noMatch = {match: false, pathIndex: 0, commandIndex: 0}; while (currentPathIndex < segmentGroup.segments.length) { if (currentCommandIndex >= commands.length) return noMatch; const path = segmentGroup.segments[currentPathIndex]; const command = commands[currentCommandIndex]; // Do not try to consume command as part of the prefixing if it has outlets because it can // contain outlets other than the one being processed. Consuming the outlets command would // result in other outlets being ignored. if (isCommandWithOutlets(command)) { break; } const curr = `${command}`; const next = currentCommandIndex < commands.length - 1 ? commands[currentCommandIndex + 1] : null; if (currentPathIndex > 0 && curr === undefined) break; if (curr && next && typeof next === 'object' && next.outlets === undefined) { if (!compare(curr, next, path)) return noMatch; currentCommandIndex += 2; } else { if (!compare(curr, {}, path)) return noMatch; currentCommandIndex++; } currentPathIndex++; } return {match: true, pathIndex: currentPathIndex, commandIndex: currentCommandIndex}; } function createNewSegmentGroup( segmentGroup: UrlSegmentGroup, startIndex: number, commands: any[], ): UrlSegmentGroup { const paths = segmentGroup.segments.slice(0, startIndex); let i = 0; while (i < commands.length) { const command = commands[i]; if (isCommandWithOutlets(command)) { const children = createNewSegmentChildren(command.outlets); return new UrlSegmentGroup(paths, children); } // if we start with an object literal, we need to reuse the path part from the segment if (i === 0 && isMatrixParams(commands[0])) { const p = segmentGroup.segments[startIndex]; paths.push(new UrlSegment(p.path, stringify(commands[0]))); i++; continue; } const curr = isCommandWithOutlets(command) ? command.outlets[PRIMARY_OUTLET] : `${command}`; const next = i < commands.length - 1 ? commands[i + 1] : null; if (curr && next && isMatrixParams(next)) { paths.push(new UrlSegment(curr, stringify(next))); i += 2; } else { paths.push(new UrlSegment(curr, {})); i++; } } return new UrlSegmentGroup(paths, {}); } function createNewSegmentChildren(outlets: {[name: string]: unknown[] | string}): { [outlet: string]: UrlSegmentGroup; } { const children: {[outlet: string]: UrlSegmentGroup} = {}; Object.entries(outlets).forEach(([outlet, commands]) => { if (typeof commands === 'string') { commands = [commands]; } if (commands !== null) { children[outlet] = createNewSegmentGroup(new UrlSegmentGroup([], {}), 0, commands); } }); return children; } function stringify(params: {[key: string]: any}): {[key: string]: string} { const res: {[key: string]: string} = {}; Object.entries(params).forEach(([k, v]) => (res[k] = `${v}`)); return res; } function compare(path: string, params: {[key: string]: any}, segment: UrlSegment): boolean { return path == segment.path && shallowEqual(params, segment.parameters); }
{ "end_byte": 18612, "start_byte": 15297, "url": "https://github.com/angular/angular/blob/main/packages/router/src/create_url_tree.ts" }
angular/packages/router/src/router_scroller.ts_0_4665
/** * @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.dev/license */ import {ViewportScroller} from '@angular/common'; import {Injectable, InjectionToken, NgZone, OnDestroy} from '@angular/core'; import {Unsubscribable} from 'rxjs'; import { NavigationEnd, NavigationSkipped, NavigationSkippedCode, NavigationStart, Scroll, } from './events'; import {NavigationTransitions} from './navigation_transition'; import {UrlSerializer} from './url_tree'; export const ROUTER_SCROLLER = new InjectionToken<RouterScroller>(''); @Injectable() export class RouterScroller implements OnDestroy { private routerEventsSubscription?: Unsubscribable; private scrollEventsSubscription?: Unsubscribable; private lastId = 0; private lastSource: 'imperative' | 'popstate' | 'hashchange' | undefined = 'imperative'; private restoredId = 0; private store: {[key: string]: [number, number]} = {}; /** @nodoc */ constructor( readonly urlSerializer: UrlSerializer, private transitions: NavigationTransitions, public readonly viewportScroller: ViewportScroller, private readonly zone: NgZone, private options: { scrollPositionRestoration?: 'disabled' | 'enabled' | 'top'; anchorScrolling?: 'disabled' | 'enabled'; } = {}, ) { // Default both options to 'disabled' options.scrollPositionRestoration ||= 'disabled'; options.anchorScrolling ||= 'disabled'; } init(): void { // we want to disable the automatic scrolling because having two places // responsible for scrolling results race conditions, especially given // that browser don't implement this behavior consistently if (this.options.scrollPositionRestoration !== 'disabled') { this.viewportScroller.setHistoryScrollRestoration('manual'); } this.routerEventsSubscription = this.createScrollEvents(); this.scrollEventsSubscription = this.consumeScrollEvents(); } private createScrollEvents() { return this.transitions.events.subscribe((e) => { if (e instanceof NavigationStart) { // store the scroll position of the current stable navigations. this.store[this.lastId] = this.viewportScroller.getScrollPosition(); this.lastSource = e.navigationTrigger; this.restoredId = e.restoredState ? e.restoredState.navigationId : 0; } else if (e instanceof NavigationEnd) { this.lastId = e.id; this.scheduleScrollEvent(e, this.urlSerializer.parse(e.urlAfterRedirects).fragment); } else if ( e instanceof NavigationSkipped && e.code === NavigationSkippedCode.IgnoredSameUrlNavigation ) { this.lastSource = undefined; this.restoredId = 0; this.scheduleScrollEvent(e, this.urlSerializer.parse(e.url).fragment); } }); } private consumeScrollEvents() { return this.transitions.events.subscribe((e) => { if (!(e instanceof Scroll)) return; // a popstate event. The pop state event will always ignore anchor scrolling. if (e.position) { if (this.options.scrollPositionRestoration === 'top') { this.viewportScroller.scrollToPosition([0, 0]); } else if (this.options.scrollPositionRestoration === 'enabled') { this.viewportScroller.scrollToPosition(e.position); } // imperative navigation "forward" } else { if (e.anchor && this.options.anchorScrolling === 'enabled') { this.viewportScroller.scrollToAnchor(e.anchor); } else if (this.options.scrollPositionRestoration !== 'disabled') { this.viewportScroller.scrollToPosition([0, 0]); } } }); } private scheduleScrollEvent( routerEvent: NavigationEnd | NavigationSkipped, anchor: string | null, ): void { this.zone.runOutsideAngular(() => { // The scroll event needs to be delayed until after change detection. Otherwise, we may // attempt to restore the scroll position before the router outlet has fully rendered the // component by executing its update block of the template function. setTimeout(() => { this.zone.run(() => { this.transitions.events.next( new Scroll( routerEvent, this.lastSource === 'popstate' ? this.store[this.restoredId] : null, anchor, ), ); }); }, 0); }); } /** @nodoc */ ngOnDestroy() { this.routerEventsSubscription?.unsubscribe(); this.scrollEventsSubscription?.unsubscribe(); } }
{ "end_byte": 4665, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/router/src/router_scroller.ts" }
angular/packages/router/src/route_reuse_strategy.ts_0_3716
/** * @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.dev/license */ import {ComponentRef, inject, Injectable} from '@angular/core'; import {OutletContext} from './router_outlet_context'; import {ActivatedRoute, ActivatedRouteSnapshot} from './router_state'; import {TreeNode} from './utils/tree'; /** * @description * * Represents the detached route tree. * * This is an opaque value the router will give to a custom route reuse strategy * to store and retrieve later on. * * @publicApi */ export type DetachedRouteHandle = {}; /** @internal */ export type DetachedRouteHandleInternal = { contexts: Map<string, OutletContext>; componentRef: ComponentRef<any>; route: TreeNode<ActivatedRoute>; }; /** * @description * * Provides a way to customize when activated routes get reused. * * @publicApi */ @Injectable({providedIn: 'root', useFactory: () => inject(DefaultRouteReuseStrategy)}) export abstract class RouteReuseStrategy { /** Determines if this route (and its subtree) should be detached to be reused later */ abstract shouldDetach(route: ActivatedRouteSnapshot): boolean; /** * Stores the detached route. * * Storing a `null` value should erase the previously stored value. */ abstract store(route: ActivatedRouteSnapshot, handle: DetachedRouteHandle | null): void; /** Determines if this route (and its subtree) should be reattached */ abstract shouldAttach(route: ActivatedRouteSnapshot): boolean; /** Retrieves the previously stored route */ abstract retrieve(route: ActivatedRouteSnapshot): DetachedRouteHandle | null; /** Determines if a route should be reused */ abstract shouldReuseRoute(future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean; } /** * @description * * This base route reuse strategy only reuses routes when the matched router configs are * identical. This prevents components from being destroyed and recreated * when just the route parameters, query parameters or fragment change * (that is, the existing component is _reused_). * * This strategy does not store any routes for later reuse. * * Angular uses this strategy by default. * * * It can be used as a base class for custom route reuse strategies, i.e. you can create your own * class that extends the `BaseRouteReuseStrategy` one. * @publicApi */ export abstract class BaseRouteReuseStrategy implements RouteReuseStrategy { /** * Whether the given route should detach for later reuse. * Always returns false for `BaseRouteReuseStrategy`. * */ shouldDetach(route: ActivatedRouteSnapshot): boolean { return false; } /** * A no-op; the route is never stored since this strategy never detaches routes for later re-use. */ store(route: ActivatedRouteSnapshot, detachedTree: DetachedRouteHandle): void {} /** Returns `false`, meaning the route (and its subtree) is never reattached */ shouldAttach(route: ActivatedRouteSnapshot): boolean { return false; } /** Returns `null` because this strategy does not store routes for later re-use. */ retrieve(route: ActivatedRouteSnapshot): DetachedRouteHandle | null { return null; } /** * Determines if a route should be reused. * This strategy returns `true` when the future route config and current route config are * identical. */ shouldReuseRoute(future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean { return future.routeConfig === curr.routeConfig; } } @Injectable({providedIn: 'root'}) export class DefaultRouteReuseStrategy extends BaseRouteReuseStrategy {}
{ "end_byte": 3716, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/router/src/route_reuse_strategy.ts" }
angular/packages/router/src/router_state.ts_0_8121
/** * @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.dev/license */ import {Type} from '@angular/core'; import {BehaviorSubject, Observable, of} from 'rxjs'; import {map} from 'rxjs/operators'; import {Data, ResolveData, Route} from './models'; import {convertToParamMap, ParamMap, Params, PRIMARY_OUTLET, RouteTitleKey} from './shared'; import {equalSegments, UrlSegment} from './url_tree'; import {shallowEqual, shallowEqualArrays} from './utils/collection'; import {Tree, TreeNode} from './utils/tree'; /** * Represents the state of the router as a tree of activated routes. * * @usageNotes * * Every node in the route tree is an `ActivatedRoute` instance * that knows about the "consumed" URL segments, the extracted parameters, * and the resolved data. * Use the `ActivatedRoute` properties to traverse the tree from any node. * * The following fragment shows how a component gets the root node * of the current state to establish its own route tree: * * ``` * @Component({templateUrl:'template.html'}) * class MyComponent { * constructor(router: Router) { * const state: RouterState = router.routerState; * const root: ActivatedRoute = state.root; * const child = root.firstChild; * const id: Observable<string> = child.params.map(p => p.id); * //... * } * } * ``` * * @see {@link ActivatedRoute} * @see [Getting route information](guide/routing/common-router-tasks#getting-route-information) * * @publicApi */ export class RouterState extends Tree<ActivatedRoute> { /** @internal */ constructor( root: TreeNode<ActivatedRoute>, /** The current snapshot of the router state */ public snapshot: RouterStateSnapshot, ) { super(root); setRouterState(<RouterState>this, root); } override toString(): string { return this.snapshot.toString(); } } export function createEmptyState(rootComponent: Type<any> | null): RouterState { const snapshot = createEmptyStateSnapshot(rootComponent); const emptyUrl = new BehaviorSubject([new UrlSegment('', {})]); const emptyParams = new BehaviorSubject({}); const emptyData = new BehaviorSubject({}); const emptyQueryParams = new BehaviorSubject({}); const fragment = new BehaviorSubject<string | null>(''); const activated = new ActivatedRoute( emptyUrl, emptyParams, emptyQueryParams, fragment, emptyData, PRIMARY_OUTLET, rootComponent, snapshot.root, ); activated.snapshot = snapshot.root; return new RouterState(new TreeNode<ActivatedRoute>(activated, []), snapshot); } export function createEmptyStateSnapshot(rootComponent: Type<any> | null): RouterStateSnapshot { const emptyParams = {}; const emptyData = {}; const emptyQueryParams = {}; const fragment = ''; const activated = new ActivatedRouteSnapshot( [], emptyParams, emptyQueryParams, fragment, emptyData, PRIMARY_OUTLET, rootComponent, null, {}, ); return new RouterStateSnapshot('', new TreeNode<ActivatedRouteSnapshot>(activated, [])); } /** * Provides access to information about a route associated with a component * that is loaded in an outlet. * Use to traverse the `RouterState` tree and extract information from nodes. * * The following example shows how to construct a component using information from a * currently activated route. * * Note: the observables in this class only emit when the current and previous values differ based * on shallow equality. For example, changing deeply nested properties in resolved `data` will not * cause the `ActivatedRoute.data` `Observable` to emit a new value. * * {@example router/activated-route/module.ts region="activated-route" * header="activated-route.component.ts"} * * @see [Getting route information](guide/routing/common-router-tasks#getting-route-information) * * @publicApi */ export class ActivatedRoute { /** The current snapshot of this route */ snapshot!: ActivatedRouteSnapshot; /** @internal */ _futureSnapshot: ActivatedRouteSnapshot; /** @internal */ _routerState!: RouterState; /** @internal */ _paramMap?: Observable<ParamMap>; /** @internal */ _queryParamMap?: Observable<ParamMap>; /** An Observable of the resolved route title */ readonly title: Observable<string | undefined>; /** An observable of the URL segments matched by this route. */ public url: Observable<UrlSegment[]>; /** An observable of the matrix parameters scoped to this route. */ public params: Observable<Params>; /** An observable of the query parameters shared by all the routes. */ public queryParams: Observable<Params>; /** An observable of the URL fragment shared by all the routes. */ public fragment: Observable<string | null>; /** An observable of the static and resolved data of this route. */ public data: Observable<Data>; /** @internal */ constructor( /** @internal */ public urlSubject: BehaviorSubject<UrlSegment[]>, /** @internal */ public paramsSubject: BehaviorSubject<Params>, /** @internal */ public queryParamsSubject: BehaviorSubject<Params>, /** @internal */ public fragmentSubject: BehaviorSubject<string | null>, /** @internal */ public dataSubject: BehaviorSubject<Data>, /** The outlet name of the route, a constant. */ public outlet: string, /** The component of the route, a constant. */ public component: Type<any> | null, futureSnapshot: ActivatedRouteSnapshot, ) { this._futureSnapshot = futureSnapshot; this.title = this.dataSubject?.pipe(map((d: Data) => d[RouteTitleKey])) ?? of(undefined); // TODO(atscott): Verify that these can be changed to `.asObservable()` with TGP. this.url = urlSubject; this.params = paramsSubject; this.queryParams = queryParamsSubject; this.fragment = fragmentSubject; this.data = dataSubject; } /** The configuration used to match this route. */ get routeConfig(): Route | null { return this._futureSnapshot.routeConfig; } /** The root of the router state. */ get root(): ActivatedRoute { return this._routerState.root; } /** The parent of this route in the router state tree. */ get parent(): ActivatedRoute | null { return this._routerState.parent(this); } /** The first child of this route in the router state tree. */ get firstChild(): ActivatedRoute | null { return this._routerState.firstChild(this); } /** The children of this route in the router state tree. */ get children(): ActivatedRoute[] { return this._routerState.children(this); } /** The path from the root of the router state tree to this route. */ get pathFromRoot(): ActivatedRoute[] { return this._routerState.pathFromRoot(this); } /** * An Observable that contains a map of the required and optional parameters * specific to the route. * The map supports retrieving single and multiple values from the same parameter. */ get paramMap(): Observable<ParamMap> { this._paramMap ??= this.params.pipe(map((p: Params): ParamMap => convertToParamMap(p))); return this._paramMap; } /** * An Observable that contains a map of the query parameters available to all routes. * The map supports retrieving single and multiple values from the query parameter. */ get queryParamMap(): Observable<ParamMap> { this._queryParamMap ??= this.queryParams.pipe( map((p: Params): ParamMap => convertToParamMap(p)), ); return this._queryParamMap; } toString(): string { return this.snapshot ? this.snapshot.toString() : `Future(${this._futureSnapshot})`; } } export type ParamsInheritanceStrategy = 'emptyOnly' | 'always'; /** @internal */ export type Inherited = { params: Params; data: Data; resolve: Data; }; /** * Returns the inherited params, data, and resolve for a given route. * * By default, we do not inherit parent data unless the current route is path-less or the parent * route is component-less. */
{ "end_byte": 8121, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/router/src/router_state.ts" }
angular/packages/router/src/router_state.ts_8122_16722
export function getInherited( route: ActivatedRouteSnapshot, parent: ActivatedRouteSnapshot | null, paramsInheritanceStrategy: ParamsInheritanceStrategy = 'emptyOnly', ): Inherited { let inherited: Inherited; const {routeConfig} = route; if ( parent !== null && (paramsInheritanceStrategy === 'always' || // inherit parent data if route is empty path routeConfig?.path === '' || // inherit parent data if parent was componentless (!parent.component && !parent.routeConfig?.loadComponent)) ) { inherited = { params: {...parent.params, ...route.params}, data: {...parent.data, ...route.data}, resolve: { // Snapshots are created with data inherited from parent and guards (i.e. canActivate) can // change data because it's not frozen... // This first line could be deleted chose to break/disallow mutating the `data` object in // guards. // Note that data from parents still override this mutated data so anyone relying on this // might be surprised that it doesn't work if parent data is inherited but otherwise does. ...route.data, // Ensure inherited resolved data overrides inherited static data ...parent.data, // static data from the current route overrides any inherited data ...routeConfig?.data, // resolved data from current route overrides everything ...route._resolvedData, }, }; } else { inherited = { params: {...route.params}, data: {...route.data}, resolve: {...route.data, ...(route._resolvedData ?? {})}, }; } if (routeConfig && hasStaticTitle(routeConfig)) { inherited.resolve[RouteTitleKey] = routeConfig.title; } return inherited; } /** * @description * * Contains the information about a route associated with a component loaded in an * outlet at a particular moment in time. ActivatedRouteSnapshot can also be used to * traverse the router state tree. * * The following example initializes a component with route information extracted * from the snapshot of the root node at the time of creation. * * ``` * @Component({templateUrl:'./my-component.html'}) * class MyComponent { * constructor(route: ActivatedRoute) { * const id: string = route.snapshot.params.id; * const url: string = route.snapshot.url.join(''); * const user = route.snapshot.data.user; * } * } * ``` * * @publicApi */ export class ActivatedRouteSnapshot { /** The configuration used to match this route **/ public readonly routeConfig: Route | null; /** @internal */ _resolve: ResolveData; /** @internal */ _resolvedData?: Data; /** @internal */ _routerState!: RouterStateSnapshot; /** @internal */ _paramMap?: ParamMap; /** @internal */ _queryParamMap?: ParamMap; /** The resolved route title */ get title(): string | undefined { // Note: This _must_ be a getter because the data is mutated in the resolvers. Title will not be // available at the time of class instantiation. return this.data?.[RouteTitleKey]; } /** @internal */ constructor( /** The URL segments matched by this route */ public url: UrlSegment[], /** * The matrix parameters scoped to this route. * * You can compute all params (or data) in the router state or to get params outside * of an activated component by traversing the `RouterState` tree as in the following * example: * ``` * collectRouteParams(router: Router) { * let params = {}; * let stack: ActivatedRouteSnapshot[] = [router.routerState.snapshot.root]; * while (stack.length > 0) { * const route = stack.pop()!; * params = {...params, ...route.params}; * stack.push(...route.children); * } * return params; * } * ``` */ public params: Params, /** The query parameters shared by all the routes */ public queryParams: Params, /** The URL fragment shared by all the routes */ public fragment: string | null, /** The static and resolved data of this route */ public data: Data, /** The outlet name of the route */ public outlet: string, /** The component of the route */ public component: Type<any> | null, routeConfig: Route | null, resolve: ResolveData, ) { this.routeConfig = routeConfig; this._resolve = resolve; } /** The root of the router state */ get root(): ActivatedRouteSnapshot { return this._routerState.root; } /** The parent of this route in the router state tree */ get parent(): ActivatedRouteSnapshot | null { return this._routerState.parent(this); } /** The first child of this route in the router state tree */ get firstChild(): ActivatedRouteSnapshot | null { return this._routerState.firstChild(this); } /** The children of this route in the router state tree */ get children(): ActivatedRouteSnapshot[] { return this._routerState.children(this); } /** The path from the root of the router state tree to this route */ get pathFromRoot(): ActivatedRouteSnapshot[] { return this._routerState.pathFromRoot(this); } get paramMap(): ParamMap { this._paramMap ??= convertToParamMap(this.params); return this._paramMap; } get queryParamMap(): ParamMap { this._queryParamMap ??= convertToParamMap(this.queryParams); return this._queryParamMap; } toString(): string { const url = this.url.map((segment) => segment.toString()).join('/'); const matched = this.routeConfig ? this.routeConfig.path : ''; return `Route(url:'${url}', path:'${matched}')`; } } /** * @description * * Represents the state of the router at a moment in time. * * This is a tree of activated route snapshots. Every node in this tree knows about * the "consumed" URL segments, the extracted parameters, and the resolved data. * * The following example shows how a component is initialized with information * from the snapshot of the root node's state at the time of creation. * * ``` * @Component({templateUrl:'template.html'}) * class MyComponent { * constructor(router: Router) { * const state: RouterState = router.routerState; * const snapshot: RouterStateSnapshot = state.snapshot; * const root: ActivatedRouteSnapshot = snapshot.root; * const child = root.firstChild; * const id: Observable<string> = child.params.map(p => p.id); * //... * } * } * ``` * * @publicApi */ export class RouterStateSnapshot extends Tree<ActivatedRouteSnapshot> { /** @internal */ constructor( /** The url from which this snapshot was created */ public url: string, root: TreeNode<ActivatedRouteSnapshot>, ) { super(root); setRouterState(<RouterStateSnapshot>this, root); } override toString(): string { return serializeNode(this._root); } } function setRouterState<U, T extends {_routerState: U}>(state: U, node: TreeNode<T>): void { node.value._routerState = state; node.children.forEach((c) => setRouterState(state, c)); } function serializeNode(node: TreeNode<ActivatedRouteSnapshot>): string { const c = node.children.length > 0 ? ` { ${node.children.map(serializeNode).join(', ')} } ` : ''; return `${node.value}${c}`; } /** * The expectation is that the activate route is created with the right set of parameters. * So we push new values into the observables only when they are not the initial values. * And we detect that by checking if the snapshot field is set. */ export function advanceActivatedRoute(route: ActivatedRoute): void { if (route.snapshot) { const currentSnapshot = route.snapshot; const nextSnapshot = route._futureSnapshot; route.snapshot = nextSnapshot; if (!shallowEqual(currentSnapshot.queryParams, nextSnapshot.queryParams)) { route.queryParamsSubject.next(nextSnapshot.queryParams); } if (currentSnapshot.fragment !== nextSnapshot.fragment) { route.fragmentSubject.next(nextSnapshot.fragment); } if (!shallowEqual(currentSnapshot.params, nextSnapshot.params)) { route.paramsSubject.next(nextSnapshot.params); } if (!shallowEqualArrays(currentSnapshot.url, nextSnapshot.url)) { route.urlSubject.next(nextSnapshot.url); } if (!shallowEqual(currentSnapshot.data, nextSnapshot.data)) { route.dataSubject.next(nextSnapshot.data); } } else { route.snapshot = route._futureSnapshot; // this is for resolved data route.dataSubject.next(route._futureSnapshot.data); } }
{ "end_byte": 16722, "start_byte": 8122, "url": "https://github.com/angular/angular/blob/main/packages/router/src/router_state.ts" }
angular/packages/router/src/router_state.ts_16724_17228
export function equalParamsAndUrlSegments( a: ActivatedRouteSnapshot, b: ActivatedRouteSnapshot, ): boolean { const equalUrlParams = shallowEqual(a.params, b.params) && equalSegments(a.url, b.url); const parentsMismatch = !a.parent !== !b.parent; return ( equalUrlParams && !parentsMismatch && (!a.parent || equalParamsAndUrlSegments(a.parent, b.parent!)) ); } export function hasStaticTitle(config: Route) { return typeof config.title === 'string' || config.title === null; }
{ "end_byte": 17228, "start_byte": 16724, "url": "https://github.com/angular/angular/blob/main/packages/router/src/router_state.ts" }
angular/packages/router/src/router.ts_0_2810
/** * @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.dev/license */ import {Location} from '@angular/common'; import { inject, Injectable, Type, ɵConsole as Console, ɵPendingTasks as PendingTasks, ɵRuntimeError as RuntimeError, } from '@angular/core'; import {Observable, Subject, Subscription, SubscriptionLike} from 'rxjs'; import {createSegmentGroupFromRoute, createUrlTreeFromSegmentGroup} from './create_url_tree'; import {INPUT_BINDER} from './directives/router_outlet'; import {RuntimeErrorCode} from './errors'; import { BeforeActivateRoutes, Event, IMPERATIVE_NAVIGATION, NavigationCancel, NavigationCancellationCode, NavigationEnd, NavigationTrigger, PrivateRouterEvents, RedirectRequest, } from './events'; import {NavigationBehaviorOptions, OnSameUrlNavigation, Routes} from './models'; import { isBrowserTriggeredNavigation, Navigation, NavigationExtras, NavigationTransitions, RestoredState, UrlCreationOptions, } from './navigation_transition'; import {RouteReuseStrategy} from './route_reuse_strategy'; import {ROUTER_CONFIGURATION} from './router_config'; import {ROUTES} from './router_config_loader'; import {Params} from './shared'; import {StateManager} from './statemanager/state_manager'; import {UrlHandlingStrategy} from './url_handling_strategy'; import { containsTree, IsActiveMatchOptions, isUrlTree, UrlSegmentGroup, UrlSerializer, UrlTree, } from './url_tree'; import {validateConfig} from './utils/config'; import {afterNextNavigation} from './utils/navigations'; import {standardizeConfig} from './components/empty_outlet'; function defaultErrorHandler(error: any): never { throw error; } /** * 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 facilitates navigation among views and URL manipulation capabilities. * This service is provided in the root scope and configured with [provideRouter](api/router/provideRouter). * * @see {@link Route} * @see {@link provideRouter} * @see [Routing and Navigation Guide](guide/routing/common-router-tasks). * * @ngModule RouterModule * * @publicApi */ @Injectable({providedIn: 'root'}) export cl
{ "end_byte": 2810, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/router/src/router.ts" }
angular/packages/router/src/router.ts_2811_12277
ss Router { private get currentUrlTree() { return this.stateManager.getCurrentUrlTree(); } private get rawUrlTree() { return this.stateManager.getRawUrlTree(); } private disposed = false; private nonRouterCurrentEntryChangeSubscription?: SubscriptionLike; private readonly console = inject(Console); private readonly stateManager = inject(StateManager); private readonly options = inject(ROUTER_CONFIGURATION, {optional: true}) || {}; private readonly pendingTasks = inject(PendingTasks); private readonly urlUpdateStrategy = this.options.urlUpdateStrategy || 'deferred'; private readonly navigationTransitions = inject(NavigationTransitions); private readonly urlSerializer = inject(UrlSerializer); private readonly location = inject(Location); private readonly urlHandlingStrategy = inject(UrlHandlingStrategy); /** * The private `Subject` type for the public events exposed in the getter. This is used internally * to push events to. The separate field allows us to expose separate types in the public API * (i.e., an Observable rather than the Subject). */ private _events = new Subject<Event>(); /** * An event stream for routing events. */ public get events(): Observable<Event> { // TODO(atscott): This _should_ be events.asObservable(). However, this change requires internal // cleanup: tests are doing `(route.events as Subject<Event>).next(...)`. This isn't // allowed/supported but we still have to fix these or file bugs against the teams before making // the change. return this._events; } /** * The current state of routing in this NgModule. */ get routerState() { return this.stateManager.getRouterState(); } /** * True if at least one navigation event has occurred, * false otherwise. */ navigated: boolean = false; /** * A strategy for re-using routes. * * @deprecated Configure using `providers` instead: * `{provide: RouteReuseStrategy, useClass: MyStrategy}`. */ routeReuseStrategy: RouteReuseStrategy = inject(RouteReuseStrategy); /** * How to handle a navigation request to the current URL. * * * @deprecated Configure this through `provideRouter` or `RouterModule.forRoot` instead. * @see {@link withRouterConfig} * @see {@link provideRouter} * @see {@link RouterModule} */ onSameUrlNavigation: OnSameUrlNavigation = this.options.onSameUrlNavigation || 'ignore'; config: Routes = inject(ROUTES, {optional: true})?.flat() ?? []; /** * Indicates whether the application has opted in to binding Router data to component inputs. * * This option is enabled by the `withComponentInputBinding` feature of `provideRouter` or * `bindToComponentInputs` in the `ExtraOptions` of `RouterModule.forRoot`. */ readonly componentInputBindingEnabled: boolean = !!inject(INPUT_BINDER, {optional: true}); constructor() { this.resetConfig(this.config); this.navigationTransitions .setupNavigations(this, this.currentUrlTree, this.routerState) .subscribe({ error: (e) => { this.console.warn(ngDevMode ? `Unhandled Navigation Error: ${e}` : e); }, }); this.subscribeToNavigationEvents(); } private eventsSubscription = new Subscription(); private subscribeToNavigationEvents() { const subscription = this.navigationTransitions.events.subscribe((e) => { try { const currentTransition = this.navigationTransitions.currentTransition; const currentNavigation = this.navigationTransitions.currentNavigation; if (currentTransition !== null && currentNavigation !== null) { this.stateManager.handleRouterEvent(e, currentNavigation); if ( e instanceof NavigationCancel && e.code !== NavigationCancellationCode.Redirect && e.code !== NavigationCancellationCode.SupersededByNewNavigation ) { // It seems weird that `navigated` is set to `true` when the navigation is rejected, // however it's how things were written initially. Investigation would need to be done // to determine if this can be removed. this.navigated = true; } else if (e instanceof NavigationEnd) { this.navigated = true; } else if (e instanceof RedirectRequest) { const opts = e.navigationBehaviorOptions; const mergedTree = this.urlHandlingStrategy.merge( e.url, currentTransition.currentRawUrl, ); const extras = { browserUrl: currentTransition.extras.browserUrl, info: currentTransition.extras.info, skipLocationChange: currentTransition.extras.skipLocationChange, // The URL is already updated at this point if we have 'eager' URL // updates or if the navigation was triggered by the browser (back // button, URL bar, etc). We want to replace that item in history // if the navigation is rejected. replaceUrl: currentTransition.extras.replaceUrl || this.urlUpdateStrategy === 'eager' || isBrowserTriggeredNavigation(currentTransition.source), // allow developer to override default options with RedirectCommand ...opts, }; this.scheduleNavigation(mergedTree, IMPERATIVE_NAVIGATION, null, extras, { resolve: currentTransition.resolve, reject: currentTransition.reject, promise: currentTransition.promise, }); } } // Note that it's important to have the Router process the events _before_ the event is // pushed through the public observable. This ensures the correct router state is in place // before applications observe the events. if (isPublicRouterEvent(e)) { this._events.next(e); } } catch (e: unknown) { this.navigationTransitions.transitionAbortSubject.next(e as Error); } }); this.eventsSubscription.add(subscription); } /** @internal */ resetRootComponentType(rootComponentType: Type<any>): void { // TODO: vsavkin router 4.0 should make the root component set to null // this will simplify the lifecycle of the router. this.routerState.root.component = rootComponentType; this.navigationTransitions.rootComponentType = rootComponentType; } /** * Sets up the location change listener and performs the initial navigation. */ initialNavigation(): void { this.setUpLocationChangeListener(); if (!this.navigationTransitions.hasRequestedNavigation) { this.navigateToSyncWithBrowser( this.location.path(true), IMPERATIVE_NAVIGATION, this.stateManager.restoredState(), ); } } /** * Sets up the location change listener. This listener detects navigations triggered from outside * the Router (the browser back/forward buttons, for example) and schedules a corresponding Router * navigation so that the correct events, guards, etc. are triggered. */ setUpLocationChangeListener(): void { // Don't need to use Zone.wrap any more, because zone.js // already patch onPopState, so location change callback will // run into ngZone this.nonRouterCurrentEntryChangeSubscription ??= this.stateManager.registerNonRouterCurrentEntryChangeListener((url, state) => { // The `setTimeout` was added in #12160 and is likely to support Angular/AngularJS // hybrid apps. setTimeout(() => { this.navigateToSyncWithBrowser(url, 'popstate', state); }, 0); }); } /** * Schedules a router navigation to synchronize Router state with the browser state. * * This is done as a response to a popstate event and the initial navigation. These * two scenarios represent times when the browser URL/state has been updated and * the Router needs to respond to ensure its internal state matches. */ private navigateToSyncWithBrowser( url: string, source: NavigationTrigger, state: RestoredState | null | undefined, ) { const extras: NavigationExtras = {replaceUrl: true}; // TODO: restoredState should always include the entire state, regardless // of navigationId. This requires a breaking change to update the type on // NavigationStart’s restoredState, which currently requires navigationId // to always be present. The Router used to only restore history state if // a navigationId was present. // The stored navigationId is used by the RouterScroller to retrieve the scroll // position for the page. const restoredState = state?.navigationId ? state : null; // Separate to NavigationStart.restoredState, we must also restore the state to // history.state and generate a new navigationId, since it will be overwritten if (state) { const stateCopy = {...state} as Partial<RestoredState>; delete stateCopy.navigationId; delete stateCopy.ɵrouterPageId; if (Object.keys(stateCopy).length !== 0) { extras.state = stateCopy; } } const urlTree = this.parseUrl(url); this.scheduleNavigation(urlTree, source, restoredState, extras); } /** The current URL. */ get url(): string { return this.serializeUrl(this.currentUrlTree); } /*
{ "end_byte": 12277, "start_byte": 2811, "url": "https://github.com/angular/angular/blob/main/packages/router/src/router.ts" }
angular/packages/router/src/router.ts_12281_20445
* Returns the current `Navigation` object when the router is navigating, * and `null` when idle. */ getCurrentNavigation(): Navigation | null { return this.navigationTransitions.currentNavigation; } /** * The `Navigation` object of the most recent navigation to succeed and `null` if there * has not been a successful navigation yet. */ get lastSuccessfulNavigation(): Navigation | null { return this.navigationTransitions.lastSuccessfulNavigation; } /** * Resets the route configuration used for navigation and generating links. * * @param config The route array for the new configuration. * * @usageNotes * * ``` * router.resetConfig([ * { path: 'team/:id', component: TeamCmp, children: [ * { path: 'simple', component: SimpleCmp }, * { path: 'user/:name', component: UserCmp } * ]} * ]); * ``` */ resetConfig(config: Routes): void { (typeof ngDevMode === 'undefined' || ngDevMode) && validateConfig(config); this.config = config.map(standardizeConfig); this.navigated = false; } /** @nodoc */ ngOnDestroy(): void { this.dispose(); } /** Disposes of the router. */ dispose(): void { this.navigationTransitions.complete(); if (this.nonRouterCurrentEntryChangeSubscription) { this.nonRouterCurrentEntryChangeSubscription.unsubscribe(); this.nonRouterCurrentEntryChangeSubscription = undefined; } this.disposed = true; this.eventsSubscription.unsubscribe(); } /** * Appends URL segments to the current URL tree to create a new URL tree. * * @param commands An array of URL fragments with which to construct the new URL tree. * If the path is static, can be the literal URL string. For a dynamic path, pass an array of path * segments, followed by the parameters for each segment. * The fragments are applied to the current URL tree or the one provided in the `relativeTo` * property of the options object, if supplied. * @param navigationExtras Options that control the navigation strategy. * @returns The new URL tree. * * @usageNotes * * ``` * // create /team/33/user/11 * router.createUrlTree(['/team', 33, 'user', 11]); * * // create /team/33;expand=true/user/11 * router.createUrlTree(['/team', 33, {expand: true}, 'user', 11]); * * // you can collapse static segments like this (this works only with the first passed-in value): * router.createUrlTree(['/team/33/user', userId]); * * // If the first segment can contain slashes, and you do not want the router to split it, * // you can do the following: * router.createUrlTree([{segmentPath: '/one/two'}]); * * // create /team/33/(user/11//right:chat) * router.createUrlTree(['/team', 33, {outlets: {primary: 'user/11', right: 'chat'}}]); * * // remove the right secondary node * router.createUrlTree(['/team', 33, {outlets: {primary: 'user/11', right: null}}]); * * // assuming the current url is `/team/33/user/11` and the route points to `user/11` * * // navigate to /team/33/user/11/details * router.createUrlTree(['details'], {relativeTo: route}); * * // navigate to /team/33/user/22 * router.createUrlTree(['../22'], {relativeTo: route}); * * // navigate to /team/44/user/22 * router.createUrlTree(['../../team/44/user/22'], {relativeTo: route}); * * Note that a value of `null` or `undefined` for `relativeTo` indicates that the * tree should be created relative to the root. * ``` */ createUrlTree(commands: any[], navigationExtras: UrlCreationOptions = {}): UrlTree { const {relativeTo, queryParams, fragment, queryParamsHandling, preserveFragment} = navigationExtras; const f = preserveFragment ? this.currentUrlTree.fragment : fragment; let q: Params | null = null; switch (queryParamsHandling ?? this.options.defaultQueryParamsHandling) { case 'merge': q = {...this.currentUrlTree.queryParams, ...queryParams}; break; case 'preserve': q = this.currentUrlTree.queryParams; break; default: q = queryParams || null; } if (q !== null) { q = this.removeEmptyProps(q); } let relativeToUrlSegmentGroup: UrlSegmentGroup | undefined; try { const relativeToSnapshot = relativeTo ? relativeTo.snapshot : this.routerState.snapshot.root; relativeToUrlSegmentGroup = createSegmentGroupFromRoute(relativeToSnapshot); } catch (e: unknown) { // This is strictly for backwards compatibility with tests that create // invalid `ActivatedRoute` mocks. // Note: the difference between having this fallback for invalid `ActivatedRoute` setups and // just throwing is ~500 test failures. Fixing all of those tests by hand is not feasible at // the moment. if (typeof commands[0] !== 'string' || commands[0][0] !== '/') { // Navigations that were absolute in the old way of creating UrlTrees // would still work because they wouldn't attempt to match the // segments in the `ActivatedRoute` to the `currentUrlTree` but // instead just replace the root segment with the navigation result. // Non-absolute navigations would fail to apply the commands because // the logic could not find the segment to replace (so they'd act like there were no // commands). commands = []; } relativeToUrlSegmentGroup = this.currentUrlTree.root; } return createUrlTreeFromSegmentGroup(relativeToUrlSegmentGroup, commands, q, f ?? null); } /** * Navigates to a view using an absolute route path. * * @param url An absolute path for a defined route. The function does not apply any delta to the * current URL. * @param extras An object containing properties that modify the navigation strategy. * * @returns A Promise that resolves to 'true' when navigation succeeds, * to 'false' when navigation fails, or is rejected on error. * * @usageNotes * * The following calls request navigation to an absolute path. * * ``` * router.navigateByUrl("/team/33/user/11"); * * // Navigate without updating the URL * router.navigateByUrl("/team/33/user/11", { skipLocationChange: true }); * ``` * * @see [Routing and Navigation guide](guide/routing/common-router-tasks) * */ navigateByUrl( url: string | UrlTree, extras: NavigationBehaviorOptions = { skipLocationChange: false, }, ): Promise<boolean> { const urlTree = isUrlTree(url) ? url : this.parseUrl(url); const mergedTree = this.urlHandlingStrategy.merge(urlTree, this.rawUrlTree); return this.scheduleNavigation(mergedTree, IMPERATIVE_NAVIGATION, null, extras); } /** * Navigate based on the provided array of commands and a starting point. * If no starting route is provided, the navigation is absolute. * * @param commands An array of URL fragments with which to construct the target URL. * If the path is static, can be the literal URL string. For a dynamic path, pass an array of path * segments, followed by the parameters for each segment. * The fragments are applied to the current URL or the one provided in the `relativeTo` property * of the options object, if supplied. * @param extras An options object that determines how the URL should be constructed or * interpreted. * * @returns A Promise that resolves to `true` when navigation succeeds, or `false` when navigation * fails. The Promise is rejected when an error occurs if `resolveNavigationPromiseOnError` is * not `true`. * * @usageNotes * * The following calls request navigation to a dynamic route path relative to the current URL. * * ``` * router.navigate(['team', 33, 'user', 11], {relativeTo: route}); * * // Navigate without updating the URL, overriding the default behavior * router.navigate(['team', 33, 'user', 11], {relativeTo: route, skipLocationChange: true}); * ``` * * @see [Routing and Navigation guide](guide/routing/common-router-tasks) * */ nav
{ "end_byte": 20445, "start_byte": 12281, "url": "https://github.com/angular/angular/blob/main/packages/router/src/router.ts" }
angular/packages/router/src/router.ts_20448_24791
te( commands: any[], extras: NavigationExtras = {skipLocationChange: false}, ): Promise<boolean> { validateCommands(commands); return this.navigateByUrl(this.createUrlTree(commands, extras), extras); } /** Serializes a `UrlTree` into a string */ serializeUrl(url: UrlTree): string { return this.urlSerializer.serialize(url); } /** Parses a string into a `UrlTree` */ parseUrl(url: string): UrlTree { try { return this.urlSerializer.parse(url); } catch { return this.urlSerializer.parse('/'); } } /** * Returns whether the url is activated. * * @deprecated * Use `IsActiveMatchOptions` instead. * * - The equivalent `IsActiveMatchOptions` for `true` is * `{paths: 'exact', queryParams: 'exact', fragment: 'ignored', matrixParams: 'ignored'}`. * - The equivalent for `false` is * `{paths: 'subset', queryParams: 'subset', fragment: 'ignored', matrixParams: 'ignored'}`. */ isActive(url: string | UrlTree, exact: boolean): boolean; /** * Returns whether the url is activated. */ isActive(url: string | UrlTree, matchOptions: IsActiveMatchOptions): boolean; /** @internal */ isActive(url: string | UrlTree, matchOptions: boolean | IsActiveMatchOptions): boolean; isActive(url: string | UrlTree, matchOptions: boolean | IsActiveMatchOptions): boolean { let options: IsActiveMatchOptions; if (matchOptions === true) { options = {...exactMatchOptions}; } else if (matchOptions === false) { options = {...subsetMatchOptions}; } else { options = matchOptions; } if (isUrlTree(url)) { return containsTree(this.currentUrlTree, url, options); } const urlTree = this.parseUrl(url); return containsTree(this.currentUrlTree, urlTree, options); } private removeEmptyProps(params: Params): Params { return Object.entries(params).reduce((result: Params, [key, value]: [string, any]) => { if (value !== null && value !== undefined) { result[key] = value; } return result; }, {}); } private scheduleNavigation( rawUrl: UrlTree, source: NavigationTrigger, restoredState: RestoredState | null, extras: NavigationExtras, priorPromise?: { resolve: (result: boolean | PromiseLike<boolean>) => void; reject: (reason?: any) => void; promise: Promise<boolean>; }, ): Promise<boolean> { if (this.disposed) { return Promise.resolve(false); } let resolve: (result: boolean | PromiseLike<boolean>) => void; let reject: (reason?: any) => void; let promise: Promise<boolean>; if (priorPromise) { resolve = priorPromise.resolve; reject = priorPromise.reject; promise = priorPromise.promise; } else { promise = new Promise<boolean>((res, rej) => { resolve = res; reject = rej; }); } // Indicate that the navigation is happening. const taskId = this.pendingTasks.add(); afterNextNavigation(this, () => { // Remove pending task in a microtask to allow for cancelled // initial navigations and redirects within the same task. queueMicrotask(() => this.pendingTasks.remove(taskId)); }); this.navigationTransitions.handleNavigationRequest({ source, restoredState, currentUrlTree: this.currentUrlTree, currentRawUrl: this.currentUrlTree, rawUrl, extras, resolve: resolve!, reject: reject!, promise, currentSnapshot: this.routerState.snapshot, currentRouterState: this.routerState, }); // Make sure that the error is propagated even though `processNavigations` catch // handler does not rethrow return promise.catch((e: any) => { return Promise.reject(e); }); } } function validateCommands(commands: string[]): void { for (let i = 0; i < commands.length; i++) { const cmd = commands[i]; if (cmd == null) { throw new RuntimeError( RuntimeErrorCode.NULLISH_COMMAND, (typeof ngDevMode === 'undefined' || ngDevMode) && `The requested path contains ${cmd} segment at index ${i}`, ); } } } function isPublicRouterEvent(e: Event | PrivateRouterEvents): e is Event { return !(e instanceof BeforeActivateRoutes) && !(e instanceof RedirectRequest); }
{ "end_byte": 24791, "start_byte": 20448, "url": "https://github.com/angular/angular/blob/main/packages/router/src/router.ts" }
angular/packages/router/src/apply_redirects.ts_0_6052
/** * @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.dev/license */ import {Injector, runInInjectionContext, ɵRuntimeError as RuntimeError} from '@angular/core'; import {Observable, of, throwError} from 'rxjs'; import {RuntimeErrorCode} from './errors'; import {NavigationCancellationCode} from './events'; import {LoadedRouterConfig, RedirectFunction, Route} from './models'; import {navigationCancelingError} from './navigation_canceling_error'; import {ActivatedRouteSnapshot} from './router_state'; import {Params, PRIMARY_OUTLET} from './shared'; import {UrlSegment, UrlSegmentGroup, UrlSerializer, UrlTree} from './url_tree'; export class NoMatch { public segmentGroup: UrlSegmentGroup | null; constructor(segmentGroup?: UrlSegmentGroup) { this.segmentGroup = segmentGroup || null; } } export class AbsoluteRedirect extends Error { constructor(public urlTree: UrlTree) { super(); } } export function noMatch(segmentGroup: UrlSegmentGroup): Observable<any> { return throwError(new NoMatch(segmentGroup)); } export function absoluteRedirect(newTree: UrlTree): Observable<any> { return throwError(new AbsoluteRedirect(newTree)); } export function namedOutletsRedirect(redirectTo: string): Observable<any> { return throwError( new RuntimeError( RuntimeErrorCode.NAMED_OUTLET_REDIRECT, (typeof ngDevMode === 'undefined' || ngDevMode) && `Only absolute redirects can have named outlets. redirectTo: '${redirectTo}'`, ), ); } export function canLoadFails(route: Route): Observable<LoadedRouterConfig> { return throwError( navigationCancelingError( (typeof ngDevMode === 'undefined' || ngDevMode) && `Cannot load children because the guard of the route "path: '${route.path}'" returned false`, NavigationCancellationCode.GuardRejected, ), ); } export class ApplyRedirects { constructor( private urlSerializer: UrlSerializer, private urlTree: UrlTree, ) {} lineralizeSegments(route: Route, urlTree: UrlTree): Observable<UrlSegment[]> { let res: UrlSegment[] = []; let c = urlTree.root; while (true) { res = res.concat(c.segments); if (c.numberOfChildren === 0) { return of(res); } if (c.numberOfChildren > 1 || !c.children[PRIMARY_OUTLET]) { return namedOutletsRedirect(`${route.redirectTo!}`); } c = c.children[PRIMARY_OUTLET]; } } applyRedirectCommands( segments: UrlSegment[], redirectTo: string | RedirectFunction, posParams: {[k: string]: UrlSegment}, currentSnapshot: ActivatedRouteSnapshot, injector: Injector, ): UrlTree { if (typeof redirectTo !== 'string') { const redirectToFn = redirectTo; const {queryParams, fragment, routeConfig, url, outlet, params, data, title} = currentSnapshot; const newRedirect = runInInjectionContext(injector, () => redirectToFn({params, data, queryParams, fragment, routeConfig, url, outlet, title}), ); if (newRedirect instanceof UrlTree) { throw new AbsoluteRedirect(newRedirect); } redirectTo = newRedirect; } const newTree = this.applyRedirectCreateUrlTree( redirectTo, this.urlSerializer.parse(redirectTo), segments, posParams, ); if (redirectTo[0] === '/') { throw new AbsoluteRedirect(newTree); } return newTree; } applyRedirectCreateUrlTree( redirectTo: string, urlTree: UrlTree, segments: UrlSegment[], posParams: {[k: string]: UrlSegment}, ): UrlTree { const newRoot = this.createSegmentGroup(redirectTo, urlTree.root, segments, posParams); return new UrlTree( newRoot, this.createQueryParams(urlTree.queryParams, this.urlTree.queryParams), urlTree.fragment, ); } createQueryParams(redirectToParams: Params, actualParams: Params): Params { const res: Params = {}; Object.entries(redirectToParams).forEach(([k, v]) => { const copySourceValue = typeof v === 'string' && v[0] === ':'; if (copySourceValue) { const sourceName = v.substring(1); res[k] = actualParams[sourceName]; } else { res[k] = v; } }); return res; } createSegmentGroup( redirectTo: string, group: UrlSegmentGroup, segments: UrlSegment[], posParams: {[k: string]: UrlSegment}, ): UrlSegmentGroup { const updatedSegments = this.createSegments(redirectTo, group.segments, segments, posParams); let children: {[n: string]: UrlSegmentGroup} = {}; Object.entries(group.children).forEach(([name, child]) => { children[name] = this.createSegmentGroup(redirectTo, child, segments, posParams); }); return new UrlSegmentGroup(updatedSegments, children); } createSegments( redirectTo: string, redirectToSegments: UrlSegment[], actualSegments: UrlSegment[], posParams: {[k: string]: UrlSegment}, ): UrlSegment[] { return redirectToSegments.map((s) => s.path[0] === ':' ? this.findPosParam(redirectTo, s, posParams) : this.findOrReturn(s, actualSegments), ); } findPosParam( redirectTo: string, redirectToUrlSegment: UrlSegment, posParams: {[k: string]: UrlSegment}, ): UrlSegment { const pos = posParams[redirectToUrlSegment.path.substring(1)]; if (!pos) throw new RuntimeError( RuntimeErrorCode.MISSING_REDIRECT, (typeof ngDevMode === 'undefined' || ngDevMode) && `Cannot redirect to '${redirectTo}'. Cannot find '${redirectToUrlSegment.path}'.`, ); return pos; } findOrReturn(redirectToUrlSegment: UrlSegment, actualSegments: UrlSegment[]): UrlSegment { let idx = 0; for (const s of actualSegments) { if (s.path === redirectToUrlSegment.path) { actualSegments.splice(idx); return s; } idx++; } return redirectToUrlSegment; } }
{ "end_byte": 6052, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/router/src/apply_redirects.ts" }
angular/packages/router/src/errors.ts_0_932
/** * @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.dev/license */ /** * The list of error codes used in runtime code of the `router` package. * Reserved error code range: 4000-4999. */ export const enum RuntimeErrorCode { NAMED_OUTLET_REDIRECT = 4000, MISSING_REDIRECT = 4001, NO_MATCH = 4002, ROOT_SEGMENT_MATRIX_PARAMS = 4003, MISPLACED_OUTLETS_COMMAND = 4004, INVALID_DOUBLE_DOTS = 4005, TWO_SEGMENTS_WITH_SAME_OUTLET = 4006, FOR_ROOT_CALLED_TWICE = 4007, NULLISH_COMMAND = 4008, EMPTY_PATH_WITH_PARAMS = 4009, UNPARSABLE_URL = 4010, UNEXPECTED_VALUE_IN_URL = 4011, OUTLET_NOT_ACTIVATED = 4012, OUTLET_ALREADY_ACTIVATED = 4013, INVALID_ROUTE_CONFIG = 4014, INVALID_ROOT_URL_SEGMENT = 4015, INFINITE_REDIRECT = 4016, INVALID_ROUTER_LINK_INPUTS = 4016, }
{ "end_byte": 932, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/router/src/errors.ts" }
angular/packages/router/src/router_preloader.ts_0_5911
/** * @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.dev/license */ import { Compiler, createEnvironmentInjector, EnvironmentInjector, Injectable, OnDestroy, } from '@angular/core'; import {from, Observable, of, Subscription} from 'rxjs'; import {catchError, concatMap, filter, mergeAll, mergeMap} from 'rxjs/operators'; import {Event, NavigationEnd} from './events'; import {LoadedRouterConfig, Route, Routes} from './models'; import {Router} from './router'; import {RouterConfigLoader} from './router_config_loader'; /** * @description * * Provides a preloading strategy. * * @publicApi */ export abstract class PreloadingStrategy { abstract preload(route: Route, fn: () => Observable<any>): Observable<any>; } /** * @description * * Provides a preloading strategy that preloads all modules as quickly as possible. * * ``` * RouterModule.forRoot(ROUTES, {preloadingStrategy: PreloadAllModules}) * ``` * * @publicApi */ @Injectable({providedIn: 'root'}) export class PreloadAllModules implements PreloadingStrategy { preload(route: Route, fn: () => Observable<any>): Observable<any> { return fn().pipe(catchError(() => of(null))); } } /** * @description * * Provides a preloading strategy that does not preload any modules. * * This strategy is enabled by default. * * @publicApi */ @Injectable({providedIn: 'root'}) export class NoPreloading implements PreloadingStrategy { preload(route: Route, fn: () => Observable<any>): Observable<any> { return of(null); } } /** * The preloader optimistically loads all router configurations to * make navigations into lazily-loaded sections of the application faster. * * The preloader runs in the background. When the router bootstraps, the preloader * starts listening to all navigation events. After every such event, the preloader * will check if any configurations can be loaded lazily. * * If a route is protected by `canLoad` guards, the preloaded will not load it. * * @publicApi */ @Injectable({providedIn: 'root'}) export class RouterPreloader implements OnDestroy { private subscription?: Subscription; constructor( private router: Router, compiler: Compiler, private injector: EnvironmentInjector, private preloadingStrategy: PreloadingStrategy, private loader: RouterConfigLoader, ) {} setUpPreloading(): void { this.subscription = this.router.events .pipe( filter((e: Event) => e instanceof NavigationEnd), concatMap(() => this.preload()), ) .subscribe(() => {}); } preload(): Observable<any> { return this.processRoutes(this.injector, this.router.config); } /** @nodoc */ ngOnDestroy(): void { if (this.subscription) { this.subscription.unsubscribe(); } } private processRoutes(injector: EnvironmentInjector, routes: Routes): Observable<void> { const res: Observable<any>[] = []; for (const route of routes) { if (route.providers && !route._injector) { route._injector = createEnvironmentInjector( route.providers, injector, `Route: ${route.path}`, ); } const injectorForCurrentRoute = route._injector ?? injector; const injectorForChildren = route._loadedInjector ?? injectorForCurrentRoute; // Note that `canLoad` is only checked as a condition that prevents `loadChildren` and not // `loadComponent`. `canLoad` guards only block loading of child routes by design. This // happens as a consequence of needing to descend into children for route matching immediately // while component loading is deferred until route activation. Because `canLoad` guards can // have side effects, we cannot execute them here so we instead skip preloading altogether // when present. Lastly, it remains to be decided whether `canLoad` should behave this way // at all. Code splitting and lazy loading is separate from client-side authorization checks // and should not be used as a security measure to prevent loading of code. if ( (route.loadChildren && !route._loadedRoutes && route.canLoad === undefined) || (route.loadComponent && !route._loadedComponent) ) { res.push(this.preloadConfig(injectorForCurrentRoute, route)); } if (route.children || route._loadedRoutes) { res.push(this.processRoutes(injectorForChildren, (route.children ?? route._loadedRoutes)!)); } } return from(res).pipe(mergeAll()); } private preloadConfig(injector: EnvironmentInjector, route: Route): Observable<void> { return this.preloadingStrategy.preload(route, () => { let loadedChildren$: Observable<LoadedRouterConfig | null>; if (route.loadChildren && route.canLoad === undefined) { loadedChildren$ = this.loader.loadChildren(injector, route); } else { loadedChildren$ = of(null); } const recursiveLoadChildren$ = loadedChildren$.pipe( mergeMap((config: LoadedRouterConfig | null) => { if (config === null) { return of(void 0); } route._loadedRoutes = config.routes; route._loadedInjector = config.injector; // If the loaded config was a module, use that as the module/module injector going // forward. Otherwise, continue using the current module/module injector. return this.processRoutes(config.injector ?? injector, config.routes); }), ); if (route.loadComponent && !route._loadedComponent) { const loadComponent$ = this.loader.loadComponent(route); return from([recursiveLoadChildren$, loadComponent$]).pipe(mergeAll()); } else { return recursiveLoadChildren$; } }); } }
{ "end_byte": 5911, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/router/src/router_preloader.ts" }
angular/packages/router/src/url_tree.ts_0_7487
/** * @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.dev/license */ import {Injectable, ɵRuntimeError as RuntimeError} from '@angular/core'; import {RuntimeErrorCode} from './errors'; import {convertToParamMap, ParamMap, Params, PRIMARY_OUTLET} from './shared'; import {equalArraysOrString, shallowEqual} from './utils/collection'; /** * A set of options which specify how to determine if a `UrlTree` is active, given the `UrlTree` * for the current router state. * * @publicApi * @see {@link Router#isActive} */ export interface IsActiveMatchOptions { /** * Defines the strategy for comparing the matrix parameters of two `UrlTree`s. * * The matrix parameter matching is dependent on the strategy for matching the * segments. That is, if the `paths` option is set to `'subset'`, only * the matrix parameters of the matching segments will be compared. * * - `'exact'`: Requires that matching segments also have exact matrix parameter * matches. * - `'subset'`: The matching segments in the router's active `UrlTree` may contain * extra matrix parameters, but those that exist in the `UrlTree` in question must match. * - `'ignored'`: When comparing `UrlTree`s, matrix params will be ignored. */ matrixParams: 'exact' | 'subset' | 'ignored'; /** * Defines the strategy for comparing the query parameters of two `UrlTree`s. * * - `'exact'`: the query parameters must match exactly. * - `'subset'`: the active `UrlTree` may contain extra parameters, * but must match the key and value of any that exist in the `UrlTree` in question. * - `'ignored'`: When comparing `UrlTree`s, query params will be ignored. */ queryParams: 'exact' | 'subset' | 'ignored'; /** * Defines the strategy for comparing the `UrlSegment`s of the `UrlTree`s. * * - `'exact'`: all segments in each `UrlTree` must match. * - `'subset'`: a `UrlTree` will be determined to be active if it * is a subtree of the active route. That is, the active route may contain extra * segments, but must at least have all the segments of the `UrlTree` in question. */ paths: 'exact' | 'subset'; /** * - `'exact'`: indicates that the `UrlTree` fragments must be equal. * - `'ignored'`: the fragments will not be compared when determining if a * `UrlTree` is active. */ fragment: 'exact' | 'ignored'; } type ParamMatchOptions = 'exact' | 'subset' | 'ignored'; type PathCompareFn = ( container: UrlSegmentGroup, containee: UrlSegmentGroup, matrixParams: ParamMatchOptions, ) => boolean; type ParamCompareFn = (container: Params, containee: Params) => boolean; const pathCompareMap: Record<IsActiveMatchOptions['paths'], PathCompareFn> = { 'exact': equalSegmentGroups, 'subset': containsSegmentGroup, }; const paramCompareMap: Record<ParamMatchOptions, ParamCompareFn> = { 'exact': equalParams, 'subset': containsParams, 'ignored': () => true, }; export function containsTree( container: UrlTree, containee: UrlTree, options: IsActiveMatchOptions, ): boolean { return ( pathCompareMap[options.paths](container.root, containee.root, options.matrixParams) && paramCompareMap[options.queryParams](container.queryParams, containee.queryParams) && !(options.fragment === 'exact' && container.fragment !== containee.fragment) ); } function equalParams(container: Params, containee: Params): boolean { // TODO: This does not handle array params correctly. return shallowEqual(container, containee); } function equalSegmentGroups( container: UrlSegmentGroup, containee: UrlSegmentGroup, matrixParams: ParamMatchOptions, ): boolean { if (!equalPath(container.segments, containee.segments)) return false; if (!matrixParamsMatch(container.segments, containee.segments, matrixParams)) { return false; } if (container.numberOfChildren !== containee.numberOfChildren) return false; for (const c in containee.children) { if (!container.children[c]) return false; if (!equalSegmentGroups(container.children[c], containee.children[c], matrixParams)) return false; } return true; } function containsParams(container: Params, containee: Params): boolean { return ( Object.keys(containee).length <= Object.keys(container).length && Object.keys(containee).every((key) => equalArraysOrString(container[key], containee[key])) ); } function containsSegmentGroup( container: UrlSegmentGroup, containee: UrlSegmentGroup, matrixParams: ParamMatchOptions, ): boolean { return containsSegmentGroupHelper(container, containee, containee.segments, matrixParams); } function containsSegmentGroupHelper( container: UrlSegmentGroup, containee: UrlSegmentGroup, containeePaths: UrlSegment[], matrixParams: ParamMatchOptions, ): boolean { if (container.segments.length > containeePaths.length) { const current = container.segments.slice(0, containeePaths.length); if (!equalPath(current, containeePaths)) return false; if (containee.hasChildren()) return false; if (!matrixParamsMatch(current, containeePaths, matrixParams)) return false; return true; } else if (container.segments.length === containeePaths.length) { if (!equalPath(container.segments, containeePaths)) return false; if (!matrixParamsMatch(container.segments, containeePaths, matrixParams)) return false; for (const c in containee.children) { if (!container.children[c]) return false; if (!containsSegmentGroup(container.children[c], containee.children[c], matrixParams)) { return false; } } return true; } else { const current = containeePaths.slice(0, container.segments.length); const next = containeePaths.slice(container.segments.length); if (!equalPath(container.segments, current)) return false; if (!matrixParamsMatch(container.segments, current, matrixParams)) return false; if (!container.children[PRIMARY_OUTLET]) return false; return containsSegmentGroupHelper( container.children[PRIMARY_OUTLET], containee, next, matrixParams, ); } } function matrixParamsMatch( containerPaths: UrlSegment[], containeePaths: UrlSegment[], options: ParamMatchOptions, ) { return containeePaths.every((containeeSegment, i) => { return paramCompareMap[options](containerPaths[i].parameters, containeeSegment.parameters); }); } /** * @description * * Represents the parsed URL. * * Since a router state is a tree, and the URL is nothing but a serialized state, the URL is a * serialized tree. * UrlTree is a data structure that provides a lot of affordances in dealing with URLs * * @usageNotes * ### Example * * ``` * @Component({templateUrl:'template.html'}) * class MyComponent { * constructor(router: Router) { * const tree: UrlTree = * router.parseUrl('/team/33/(user/victor//support:help)?debug=true#fragment'); * const f = tree.fragment; // return 'fragment' * const q = tree.queryParams; // returns {debug: 'true'} * const g: UrlSegmentGroup = tree.root.children[PRIMARY_OUTLET]; * const s: UrlSegment[] = g.segments; // returns 2 segments 'team' and '33' * g.children[PRIMARY_OUTLET].segments; // returns 2 segments 'user' and 'victor' * g.children['support'].segments; // return 1 segment 'help' * } * } * ``` * * @publicApi */
{ "end_byte": 7487, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/router/src/url_tree.ts" }
angular/packages/router/src/url_tree.ts_7488_15465
xport class UrlTree { /** @internal */ _queryParamMap?: ParamMap; constructor( /** The root segment group of the URL tree */ public root: UrlSegmentGroup = new UrlSegmentGroup([], {}), /** The query params of the URL */ public queryParams: Params = {}, /** The fragment of the URL */ public fragment: string | null = null, ) { if (typeof ngDevMode === 'undefined' || ngDevMode) { if (root.segments.length > 0) { throw new RuntimeError( RuntimeErrorCode.INVALID_ROOT_URL_SEGMENT, 'The root `UrlSegmentGroup` should not contain `segments`. ' + 'Instead, these segments belong in the `children` so they can be associated with a named outlet.', ); } } } get queryParamMap(): ParamMap { this._queryParamMap ??= convertToParamMap(this.queryParams); return this._queryParamMap; } /** @docsNotRequired */ toString(): string { return DEFAULT_SERIALIZER.serialize(this); } } /** * @description * * Represents the parsed URL segment group. * * See `UrlTree` for more information. * * @publicApi */ export class UrlSegmentGroup { /** The parent node in the url tree */ parent: UrlSegmentGroup | null = null; constructor( /** The URL segments of this group. See `UrlSegment` for more information */ public segments: UrlSegment[], /** The list of children of this group */ public children: {[key: string]: UrlSegmentGroup}, ) { Object.values(children).forEach((v) => (v.parent = this)); } /** Whether the segment has child segments */ hasChildren(): boolean { return this.numberOfChildren > 0; } /** Number of child segments */ get numberOfChildren(): number { return Object.keys(this.children).length; } /** @docsNotRequired */ toString(): string { return serializePaths(this); } } /** * @description * * Represents a single URL segment. * * A UrlSegment is a part of a URL between the two slashes. It contains a path and the matrix * parameters associated with the segment. * * @usageNotes * ### Example * * ``` * @Component({templateUrl:'template.html'}) * class MyComponent { * constructor(router: Router) { * const tree: UrlTree = router.parseUrl('/team;id=33'); * const g: UrlSegmentGroup = tree.root.children[PRIMARY_OUTLET]; * const s: UrlSegment[] = g.segments; * s[0].path; // returns 'team' * s[0].parameters; // returns {id: 33} * } * } * ``` * * @publicApi */ export class UrlSegment { /** @internal */ _parameterMap?: ParamMap; constructor( /** The path part of a URL segment */ public path: string, /** The matrix parameters associated with a segment */ public parameters: {[name: string]: string}, ) {} get parameterMap(): ParamMap { this._parameterMap ??= convertToParamMap(this.parameters); return this._parameterMap; } /** @docsNotRequired */ toString(): string { return serializePath(this); } } export function equalSegments(as: UrlSegment[], bs: UrlSegment[]): boolean { return equalPath(as, bs) && as.every((a, i) => shallowEqual(a.parameters, bs[i].parameters)); } export function equalPath(as: UrlSegment[], bs: UrlSegment[]): boolean { if (as.length !== bs.length) return false; return as.every((a, i) => a.path === bs[i].path); } export function mapChildrenIntoArray<T>( segment: UrlSegmentGroup, fn: (v: UrlSegmentGroup, k: string) => T[], ): T[] { let res: T[] = []; Object.entries(segment.children).forEach(([childOutlet, child]) => { if (childOutlet === PRIMARY_OUTLET) { res = res.concat(fn(child, childOutlet)); } }); Object.entries(segment.children).forEach(([childOutlet, child]) => { if (childOutlet !== PRIMARY_OUTLET) { res = res.concat(fn(child, childOutlet)); } }); return res; } /** * @description * * Serializes and deserializes a URL string into a URL tree. * * The url serialization strategy is customizable. You can * make all URLs case insensitive by providing a custom UrlSerializer. * * See `DefaultUrlSerializer` for an example of a URL serializer. * * @publicApi */ @Injectable({providedIn: 'root', useFactory: () => new DefaultUrlSerializer()}) export abstract class UrlSerializer { /** Parse a url into a `UrlTree` */ abstract parse(url: string): UrlTree; /** Converts a `UrlTree` into a url */ abstract serialize(tree: UrlTree): string; } /** * @description * * A default implementation of the `UrlSerializer`. * * Example URLs: * * ``` * /inbox/33(popup:compose) * /inbox/33;open=true/messages/44 * ``` * * DefaultUrlSerializer uses parentheses to serialize secondary segments (e.g., popup:compose), the * colon syntax to specify the outlet, and the ';parameter=value' syntax (e.g., open=true) to * specify route specific parameters. * * @publicApi */ export class DefaultUrlSerializer implements UrlSerializer { /** Parses a url into a `UrlTree` */ parse(url: string): UrlTree { const p = new UrlParser(url); return new UrlTree(p.parseRootSegment(), p.parseQueryParams(), p.parseFragment()); } /** Converts a `UrlTree` into a url */ serialize(tree: UrlTree): string { const segment = `/${serializeSegment(tree.root, true)}`; const query = serializeQueryParams(tree.queryParams); const fragment = typeof tree.fragment === `string` ? `#${encodeUriFragment(tree.fragment)}` : ''; return `${segment}${query}${fragment}`; } } const DEFAULT_SERIALIZER = new DefaultUrlSerializer(); export function serializePaths(segment: UrlSegmentGroup): string { return segment.segments.map((p) => serializePath(p)).join('/'); } function serializeSegment(segment: UrlSegmentGroup, root: boolean): string { if (!segment.hasChildren()) { return serializePaths(segment); } if (root) { const primary = segment.children[PRIMARY_OUTLET] ? serializeSegment(segment.children[PRIMARY_OUTLET], false) : ''; const children: string[] = []; Object.entries(segment.children).forEach(([k, v]) => { if (k !== PRIMARY_OUTLET) { children.push(`${k}:${serializeSegment(v, false)}`); } }); return children.length > 0 ? `${primary}(${children.join('//')})` : primary; } else { const children = mapChildrenIntoArray(segment, (v: UrlSegmentGroup, k: string) => { if (k === PRIMARY_OUTLET) { return [serializeSegment(segment.children[PRIMARY_OUTLET], false)]; } return [`${k}:${serializeSegment(v, false)}`]; }); // use no parenthesis if the only child is a primary outlet route if (Object.keys(segment.children).length === 1 && segment.children[PRIMARY_OUTLET] != null) { return `${serializePaths(segment)}/${children[0]}`; } return `${serializePaths(segment)}/(${children.join('//')})`; } } /** * Encodes a URI string with the default encoding. This function will only ever be called from * `encodeUriQuery` or `encodeUriSegment` as it's the base set of encodings to be used. We need * a custom encoding because encodeURIComponent is too aggressive and encodes stuff that doesn't * have to be encoded per https://url.spec.whatwg.org. */ function encodeUriString(s: string): string { return encodeURIComponent(s) .replace(/%40/g, '@') .replace(/%3A/gi, ':') .replace(/%24/g, '$') .replace(/%2C/gi, ','); } /** * This function should be used to encode both keys and values in a query string key/value. In * the following URL, you need to call encodeUriQuery on "k" and "v": * * http://www.site.org/html;mk=mv?k=v#f */ export function encodeUriQuery(s: string): string { return encodeUriString(s).replace(/%3B/gi, ';'); } /** * This function should be used to encode a URL fragment. In the following URL, you need to call * encodeUriFragment on "f": * * http://www.site.org/html;mk=mv?k=v#f */ export function encodeUriFragment(s: string): string { return encodeURI(s); }
{ "end_byte": 15465, "start_byte": 7488, "url": "https://github.com/angular/angular/blob/main/packages/router/src/url_tree.ts" }
angular/packages/router/src/url_tree.ts_15467_23725
* * This function should be run on any URI segment as well as the key and value in a key/value * pair for matrix params. In the following URL, you need to call encodeUriSegment on "html", * "mk", and "mv": * * http://www.site.org/html;mk=mv?k=v#f */ export function encodeUriSegment(s: string): string { return encodeUriString(s).replace(/\(/g, '%28').replace(/\)/g, '%29').replace(/%26/gi, '&'); } export function decode(s: string): string { return decodeURIComponent(s); } // Query keys/values should have the "+" replaced first, as "+" in a query string is " ". // decodeURIComponent function will not decode "+" as a space. export function decodeQuery(s: string): string { return decode(s.replace(/\+/g, '%20')); } export function serializePath(path: UrlSegment): string { return `${encodeUriSegment(path.path)}${serializeMatrixParams(path.parameters)}`; } function serializeMatrixParams(params: {[key: string]: string}): string { return Object.entries(params) .map(([key, value]) => `;${encodeUriSegment(key)}=${encodeUriSegment(value)}`) .join(''); } function serializeQueryParams(params: {[key: string]: any}): string { const strParams: string[] = Object.entries(params) .map(([name, value]) => { return Array.isArray(value) ? value.map((v) => `${encodeUriQuery(name)}=${encodeUriQuery(v)}`).join('&') : `${encodeUriQuery(name)}=${encodeUriQuery(value)}`; }) .filter((s) => s); return strParams.length ? `?${strParams.join('&')}` : ''; } const SEGMENT_RE = /^[^\/()?;#]+/; function matchSegments(str: string): string { const match = str.match(SEGMENT_RE); return match ? match[0] : ''; } const MATRIX_PARAM_SEGMENT_RE = /^[^\/()?;=#]+/; function matchMatrixKeySegments(str: string): string { const match = str.match(MATRIX_PARAM_SEGMENT_RE); return match ? match[0] : ''; } const QUERY_PARAM_RE = /^[^=?&#]+/; // Return the name of the query param at the start of the string or an empty string function matchQueryParams(str: string): string { const match = str.match(QUERY_PARAM_RE); return match ? match[0] : ''; } const QUERY_PARAM_VALUE_RE = /^[^&#]+/; // Return the value of the query param at the start of the string or an empty string function matchUrlQueryParamValue(str: string): string { const match = str.match(QUERY_PARAM_VALUE_RE); return match ? match[0] : ''; } class UrlParser { private remaining: string; constructor(private url: string) { this.remaining = url; } parseRootSegment(): UrlSegmentGroup { this.consumeOptional('/'); if (this.remaining === '' || this.peekStartsWith('?') || this.peekStartsWith('#')) { return new UrlSegmentGroup([], {}); } // The root segment group never has segments return new UrlSegmentGroup([], this.parseChildren()); } parseQueryParams(): Params { const params: Params = {}; if (this.consumeOptional('?')) { do { this.parseQueryParam(params); } while (this.consumeOptional('&')); } return params; } parseFragment(): string | null { return this.consumeOptional('#') ? decodeURIComponent(this.remaining) : null; } private parseChildren(): {[outlet: string]: UrlSegmentGroup} { if (this.remaining === '') { return {}; } this.consumeOptional('/'); const segments: UrlSegment[] = []; if (!this.peekStartsWith('(')) { segments.push(this.parseSegment()); } while (this.peekStartsWith('/') && !this.peekStartsWith('//') && !this.peekStartsWith('/(')) { this.capture('/'); segments.push(this.parseSegment()); } let children: {[outlet: string]: UrlSegmentGroup} = {}; if (this.peekStartsWith('/(')) { this.capture('/'); children = this.parseParens(true); } let res: {[outlet: string]: UrlSegmentGroup} = {}; if (this.peekStartsWith('(')) { res = this.parseParens(false); } if (segments.length > 0 || Object.keys(children).length > 0) { res[PRIMARY_OUTLET] = new UrlSegmentGroup(segments, children); } return res; } // parse a segment with its matrix parameters // ie `name;k1=v1;k2` private parseSegment(): UrlSegment { const path = matchSegments(this.remaining); if (path === '' && this.peekStartsWith(';')) { throw new RuntimeError( RuntimeErrorCode.EMPTY_PATH_WITH_PARAMS, (typeof ngDevMode === 'undefined' || ngDevMode) && `Empty path url segment cannot have parameters: '${this.remaining}'.`, ); } this.capture(path); return new UrlSegment(decode(path), this.parseMatrixParams()); } private parseMatrixParams(): {[key: string]: string} { const params: {[key: string]: string} = {}; while (this.consumeOptional(';')) { this.parseParam(params); } return params; } private parseParam(params: {[key: string]: string}): void { const key = matchMatrixKeySegments(this.remaining); if (!key) { return; } this.capture(key); let value: any = ''; if (this.consumeOptional('=')) { const valueMatch = matchSegments(this.remaining); if (valueMatch) { value = valueMatch; this.capture(value); } } params[decode(key)] = decode(value); } // Parse a single query parameter `name[=value]` private parseQueryParam(params: Params): void { const key = matchQueryParams(this.remaining); if (!key) { return; } this.capture(key); let value: any = ''; if (this.consumeOptional('=')) { const valueMatch = matchUrlQueryParamValue(this.remaining); if (valueMatch) { value = valueMatch; this.capture(value); } } const decodedKey = decodeQuery(key); const decodedVal = decodeQuery(value); if (params.hasOwnProperty(decodedKey)) { // Append to existing values let currentVal = params[decodedKey]; if (!Array.isArray(currentVal)) { currentVal = [currentVal]; params[decodedKey] = currentVal; } currentVal.push(decodedVal); } else { // Create a new value params[decodedKey] = decodedVal; } } // parse `(a/b//outlet_name:c/d)` private parseParens(allowPrimary: boolean): {[outlet: string]: UrlSegmentGroup} { const segments: {[key: string]: UrlSegmentGroup} = {}; this.capture('('); while (!this.consumeOptional(')') && this.remaining.length > 0) { const path = matchSegments(this.remaining); const next = this.remaining[path.length]; // if is is not one of these characters, then the segment was unescaped // or the group was not closed if (next !== '/' && next !== ')' && next !== ';') { throw new RuntimeError( RuntimeErrorCode.UNPARSABLE_URL, (typeof ngDevMode === 'undefined' || ngDevMode) && `Cannot parse url '${this.url}'`, ); } let outletName: string = undefined!; if (path.indexOf(':') > -1) { outletName = path.slice(0, path.indexOf(':')); this.capture(outletName); this.capture(':'); } else if (allowPrimary) { outletName = PRIMARY_OUTLET; } const children = this.parseChildren(); segments[outletName] = Object.keys(children).length === 1 ? children[PRIMARY_OUTLET] : new UrlSegmentGroup([], children); this.consumeOptional('//'); } return segments; } private peekStartsWith(str: string): boolean { return this.remaining.startsWith(str); } // Consumes the prefix when it is present and returns whether it has been consumed private consumeOptional(str: string): boolean { if (this.peekStartsWith(str)) { this.remaining = this.remaining.substring(str.length); return true; } return false; } private capture(str: string): void { if (!this.consumeOptional(str)) { throw new RuntimeError( RuntimeErrorCode.UNEXPECTED_VALUE_IN_URL, (typeof ngDevMode === 'undefined' || ngDevMode) && `Expected "${str}".`, ); } } } export function createRoot(rootCandidate: UrlSegmentGroup) { return rootCandidate.segments.length > 0 ? new UrlSegmentGroup([], {[PRIMARY_OUTLET]: rootCandidate}) : rootCandidate; }
{ "end_byte": 23725, "start_byte": 15467, "url": "https://github.com/angular/angular/blob/main/packages/router/src/url_tree.ts" }
angular/packages/router/src/url_tree.ts_23727_25956
* * Recursively * - merges primary segment children into their parents * - drops empty children (those which have no segments and no children themselves). This latter * prevents serializing a group into something like `/a(aux:)`, where `aux` is an empty child * segment. * - merges named outlets without a primary segment sibling into the children. This prevents * serializing a URL like `//(a:a)(b:b) instead of `/(a:a//b:b)` when the aux b route lives on the * root but the `a` route lives under an empty path primary route. */ export function squashSegmentGroup(segmentGroup: UrlSegmentGroup): UrlSegmentGroup { const newChildren: Record<string, UrlSegmentGroup> = {}; for (const [childOutlet, child] of Object.entries(segmentGroup.children)) { const childCandidate = squashSegmentGroup(child); // moves named children in an empty path primary child into this group if ( childOutlet === PRIMARY_OUTLET && childCandidate.segments.length === 0 && childCandidate.hasChildren() ) { for (const [grandChildOutlet, grandChild] of Object.entries(childCandidate.children)) { newChildren[grandChildOutlet] = grandChild; } } // don't add empty children else if (childCandidate.segments.length > 0 || childCandidate.hasChildren()) { newChildren[childOutlet] = childCandidate; } } const s = new UrlSegmentGroup(segmentGroup.segments, newChildren); return mergeTrivialChildren(s); } /** * When possible, merges the primary outlet child into the parent `UrlSegmentGroup`. * * When a segment group has only one child which is a primary outlet, merges that child into the * parent. That is, the child segment group's segments are merged into the `s` and the child's * children become the children of `s`. Think of this like a 'squash', merging the child segment * group into the parent. */ function mergeTrivialChildren(s: UrlSegmentGroup): UrlSegmentGroup { if (s.numberOfChildren === 1 && s.children[PRIMARY_OUTLET]) { const c = s.children[PRIMARY_OUTLET]; return new UrlSegmentGroup(s.segments.concat(c.segments), c.children); } return s; } export function isUrlTree(v: any): v is UrlTree { return v instanceof UrlTree; }
{ "end_byte": 25956, "start_byte": 23727, "url": "https://github.com/angular/angular/blob/main/packages/router/src/url_tree.ts" }
angular/packages/router/src/url_handling_strategy.ts_0_1532
/** * @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.dev/license */ import {inject, Injectable} from '@angular/core'; import {UrlTree} from './url_tree'; /** * @description * * Provides a way to migrate AngularJS applications to Angular. * * @publicApi */ @Injectable({providedIn: 'root', useFactory: () => inject(DefaultUrlHandlingStrategy)}) export abstract class UrlHandlingStrategy { /** * Tells the router if this URL should be processed. * * When it returns true, the router will execute the regular navigation. * When it returns false, the router will set the router state to an empty state. * As a result, all the active components will be destroyed. * */ abstract shouldProcessUrl(url: UrlTree): boolean; /** * Extracts the part of the URL that should be handled by the router. * The rest of the URL will remain untouched. */ abstract extract(url: UrlTree): UrlTree; /** * Merges the URL fragment with the rest of the URL. */ abstract merge(newUrlPart: UrlTree, rawUrl: UrlTree): UrlTree; } /** * @publicApi */ @Injectable({providedIn: 'root'}) export class DefaultUrlHandlingStrategy implements UrlHandlingStrategy { shouldProcessUrl(url: UrlTree): boolean { return true; } extract(url: UrlTree): UrlTree { return url; } merge(newUrlPart: UrlTree, wholeUrl: UrlTree): UrlTree { return newUrlPart; } }
{ "end_byte": 1532, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/router/src/url_handling_strategy.ts" }
angular/packages/router/src/router_config_loader.ts_0_6419
/** * @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.dev/license */ import { Compiler, EnvironmentInjector, inject, Injectable, InjectionToken, Injector, NgModuleFactory, Type, } from '@angular/core'; import {ConnectableObservable, from, Observable, of, Subject} from 'rxjs'; import {finalize, map, mergeMap, refCount, tap} from 'rxjs/operators'; import {DefaultExport, LoadedRouterConfig, Route, Routes} from './models'; import {wrapIntoObservable} from './utils/collection'; import {assertStandalone, validateConfig} from './utils/config'; import {standardizeConfig} from './components/empty_outlet'; /** * The DI token for a router configuration. * * `ROUTES` is a low level API for router configuration via dependency injection. * * We recommend that in almost all cases to use higher level APIs such as `RouterModule.forRoot()`, * `provideRouter`, or `Router.resetConfig()`. * * @publicApi */ export const ROUTES = new InjectionToken<Route[][]>(ngDevMode ? 'ROUTES' : ''); type ComponentLoader = Observable<Type<unknown>>; @Injectable({providedIn: 'root'}) export class RouterConfigLoader { private componentLoaders = new WeakMap<Route, ComponentLoader>(); private childrenLoaders = new WeakMap<Route, Observable<LoadedRouterConfig>>(); onLoadStartListener?: (r: Route) => void; onLoadEndListener?: (r: Route) => void; private readonly compiler = inject(Compiler); loadComponent(route: Route): Observable<Type<unknown>> { if (this.componentLoaders.get(route)) { return this.componentLoaders.get(route)!; } else if (route._loadedComponent) { return of(route._loadedComponent); } if (this.onLoadStartListener) { this.onLoadStartListener(route); } const loadRunner = wrapIntoObservable(route.loadComponent!()).pipe( map(maybeUnwrapDefaultExport), tap((component) => { if (this.onLoadEndListener) { this.onLoadEndListener(route); } (typeof ngDevMode === 'undefined' || ngDevMode) && assertStandalone(route.path ?? '', component); route._loadedComponent = component; }), finalize(() => { this.componentLoaders.delete(route); }), ); // Use custom ConnectableObservable as share in runners pipe increasing the bundle size too much const loader = new ConnectableObservable(loadRunner, () => new Subject<Type<unknown>>()).pipe( refCount(), ); this.componentLoaders.set(route, loader); return loader; } loadChildren(parentInjector: Injector, route: Route): Observable<LoadedRouterConfig> { if (this.childrenLoaders.get(route)) { return this.childrenLoaders.get(route)!; } else if (route._loadedRoutes) { return of({routes: route._loadedRoutes, injector: route._loadedInjector}); } if (this.onLoadStartListener) { this.onLoadStartListener(route); } const moduleFactoryOrRoutes$ = loadChildren( route, this.compiler, parentInjector, this.onLoadEndListener, ); const loadRunner = moduleFactoryOrRoutes$.pipe( finalize(() => { this.childrenLoaders.delete(route); }), ); // Use custom ConnectableObservable as share in runners pipe increasing the bundle size too much const loader = new ConnectableObservable( loadRunner, () => new Subject<LoadedRouterConfig>(), ).pipe(refCount()); this.childrenLoaders.set(route, loader); return loader; } } /** * Executes a `route.loadChildren` callback and converts the result to an array of child routes and * an injector if that callback returned a module. * * This function is used for the route discovery during prerendering * in @angular-devkit/build-angular. If there are any updates to the contract here, it will require * an update to the extractor. */ export function loadChildren( route: Route, compiler: Compiler, parentInjector: Injector, onLoadEndListener?: (r: Route) => void, ): Observable<LoadedRouterConfig> { return wrapIntoObservable(route.loadChildren!()).pipe( map(maybeUnwrapDefaultExport), mergeMap((t) => { if (t instanceof NgModuleFactory || Array.isArray(t)) { return of(t); } else { return from(compiler.compileModuleAsync(t)); } }), map((factoryOrRoutes: NgModuleFactory<any> | Routes) => { if (onLoadEndListener) { onLoadEndListener(route); } // This injector comes from the `NgModuleRef` when lazy loading an `NgModule`. There is // no injector associated with lazy loading a `Route` array. let injector: EnvironmentInjector | undefined; let rawRoutes: Route[]; let requireStandaloneComponents = false; if (Array.isArray(factoryOrRoutes)) { rawRoutes = factoryOrRoutes; requireStandaloneComponents = true; } else { injector = factoryOrRoutes.create(parentInjector).injector; // When loading a module that doesn't provide `RouterModule.forChild()` preloader // will get stuck in an infinite loop. The child module's Injector will look to // its parent `Injector` when it doesn't find any ROUTES so it will return routes // for it's parent module instead. rawRoutes = injector.get(ROUTES, [], {optional: true, self: true}).flat(); } const routes = rawRoutes.map(standardizeConfig); (typeof ngDevMode === 'undefined' || ngDevMode) && validateConfig(routes, route.path, requireStandaloneComponents); return {routes, injector}; }), ); } function isWrappedDefaultExport<T>(value: T | DefaultExport<T>): value is DefaultExport<T> { // We use `in` here with a string key `'default'`, because we expect `DefaultExport` objects to be // dynamically imported ES modules with a spec-mandated `default` key. Thus we don't expect that // `default` will be a renamed property. return value && typeof value === 'object' && 'default' in value; } function maybeUnwrapDefaultExport<T>(input: T | DefaultExport<T>): T { // As per `isWrappedDefaultExport`, the `default` key here is generated by the browser and not // subject to property renaming, so we reference it with bracket access. return isWrappedDefaultExport(input) ? input['default'] : input; }
{ "end_byte": 6419, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/router/src/router_config_loader.ts" }
angular/packages/router/src/navigation_canceling_error.ts_0_2216
/** * @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.dev/license */ import {NavigationCancellationCode} from './events'; import {NavigationBehaviorOptions, RedirectCommand} from './models'; import {isUrlTree, UrlSerializer, UrlTree} from './url_tree'; export const NAVIGATION_CANCELING_ERROR = 'ngNavigationCancelingError'; export type NavigationCancelingError = Error & { [NAVIGATION_CANCELING_ERROR]: true; cancellationCode: NavigationCancellationCode; }; export type RedirectingNavigationCancelingError = NavigationCancelingError & { url: UrlTree; navigationBehaviorOptions?: NavigationBehaviorOptions; cancellationCode: NavigationCancellationCode.Redirect; }; export function redirectingNavigationError( urlSerializer: UrlSerializer, redirect: UrlTree | RedirectCommand, ): RedirectingNavigationCancelingError { const {redirectTo, navigationBehaviorOptions} = isUrlTree(redirect) ? {redirectTo: redirect, navigationBehaviorOptions: undefined} : redirect; const error = navigationCancelingError( ngDevMode && `Redirecting to "${urlSerializer.serialize(redirectTo)}"`, NavigationCancellationCode.Redirect, ) as RedirectingNavigationCancelingError; error.url = redirectTo; error.navigationBehaviorOptions = navigationBehaviorOptions; return error; } export function navigationCancelingError( message: string | null | false, code: NavigationCancellationCode, ) { const error = new Error(`NavigationCancelingError: ${message || ''}`) as NavigationCancelingError; error[NAVIGATION_CANCELING_ERROR] = true; error.cancellationCode = code; return error; } export function isRedirectingNavigationCancelingError( error: unknown | RedirectingNavigationCancelingError, ): error is RedirectingNavigationCancelingError { return ( isNavigationCancelingError(error) && isUrlTree((error as RedirectingNavigationCancelingError).url) ); } export function isNavigationCancelingError(error: unknown): error is NavigationCancelingError { return !!error && (error as NavigationCancelingError)[NAVIGATION_CANCELING_ERROR]; }
{ "end_byte": 2216, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/router/src/navigation_canceling_error.ts" }
angular/packages/router/src/recognize.ts_0_2247
/** * @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.dev/license */ import {EnvironmentInjector, Type, ɵRuntimeError as RuntimeError} from '@angular/core'; import {from, Observable, of} from 'rxjs'; import { catchError, concatMap, defaultIfEmpty, first, last, map, mergeMap, scan, switchMap, tap, } from 'rxjs/operators'; import {AbsoluteRedirect, ApplyRedirects, canLoadFails, noMatch, NoMatch} from './apply_redirects'; import {createUrlTreeFromSnapshot} from './create_url_tree'; import {RuntimeErrorCode} from './errors'; import {Data, LoadedRouterConfig, ResolveData, Route, Routes} from './models'; import {runCanLoadGuards} from './operators/check_guards'; import {RouterConfigLoader} from './router_config_loader'; import { ActivatedRouteSnapshot, getInherited, ParamsInheritanceStrategy, RouterStateSnapshot, } from './router_state'; import {PRIMARY_OUTLET} from './shared'; import {UrlSegment, UrlSegmentGroup, UrlSerializer, UrlTree} from './url_tree'; import {getOutlet, sortByMatchingOutlets} from './utils/config'; import { emptyPathMatch, match, matchWithChecks, noLeftoversInUrl, split, } from './utils/config_matching'; import {TreeNode} from './utils/tree'; import {isEmptyError} from './utils/type_guards'; /** * Class used to indicate there were no additional route config matches but that all segments of * the URL were consumed during matching so the route was URL matched. When this happens, we still * try to match child configs in case there are empty path children. */ class NoLeftoversInUrl {} export function recognize( injector: EnvironmentInjector, configLoader: RouterConfigLoader, rootComponentType: Type<any> | null, config: Routes, urlTree: UrlTree, urlSerializer: UrlSerializer, paramsInheritanceStrategy: ParamsInheritanceStrategy = 'emptyOnly', ): Observable<{state: RouterStateSnapshot; tree: UrlTree}> { return new Recognizer( injector, configLoader, rootComponentType, config, urlTree, paramsInheritanceStrategy, urlSerializer, ).recognize(); } const MAX_ALLOWED_REDIRECTS = 31;
{ "end_byte": 2247, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/router/src/recognize.ts" }
angular/packages/router/src/recognize.ts_2249_11066
xport class Recognizer { private applyRedirects: ApplyRedirects; private absoluteRedirectCount = 0; allowRedirects = true; constructor( private injector: EnvironmentInjector, private configLoader: RouterConfigLoader, private rootComponentType: Type<any> | null, private config: Routes, private urlTree: UrlTree, private paramsInheritanceStrategy: ParamsInheritanceStrategy, private readonly urlSerializer: UrlSerializer, ) { this.applyRedirects = new ApplyRedirects(this.urlSerializer, this.urlTree); } private noMatchError(e: NoMatch): RuntimeError<RuntimeErrorCode.NO_MATCH> { return new RuntimeError( RuntimeErrorCode.NO_MATCH, typeof ngDevMode === 'undefined' || ngDevMode ? `Cannot match any routes. URL Segment: '${e.segmentGroup}'` : `'${e.segmentGroup}'`, ); } recognize(): Observable<{state: RouterStateSnapshot; tree: UrlTree}> { const rootSegmentGroup = split(this.urlTree.root, [], [], this.config).segmentGroup; return this.match(rootSegmentGroup).pipe( map(({children, rootSnapshot}) => { const rootNode = new TreeNode(rootSnapshot, children); const routeState = new RouterStateSnapshot('', rootNode); const tree = createUrlTreeFromSnapshot( rootSnapshot, [], this.urlTree.queryParams, this.urlTree.fragment, ); // https://github.com/angular/angular/issues/47307 // Creating the tree stringifies the query params // We don't want to do this here so reassign them to the original. tree.queryParams = this.urlTree.queryParams; routeState.url = this.urlSerializer.serialize(tree); return {state: routeState, tree}; }), ); } private match(rootSegmentGroup: UrlSegmentGroup): Observable<{ children: TreeNode<ActivatedRouteSnapshot>[]; rootSnapshot: ActivatedRouteSnapshot; }> { // Use Object.freeze to prevent readers of the Router state from modifying it outside // of a navigation, resulting in the router being out of sync with the browser. const rootSnapshot = new ActivatedRouteSnapshot( [], Object.freeze({}), Object.freeze({...this.urlTree.queryParams}), this.urlTree.fragment, Object.freeze({}), PRIMARY_OUTLET, this.rootComponentType, null, {}, ); return this.processSegmentGroup( this.injector, this.config, rootSegmentGroup, PRIMARY_OUTLET, rootSnapshot, ).pipe( map((children) => { return {children, rootSnapshot}; }), catchError((e: any) => { if (e instanceof AbsoluteRedirect) { this.urlTree = e.urlTree; return this.match(e.urlTree.root); } if (e instanceof NoMatch) { throw this.noMatchError(e); } throw e; }), ); } processSegmentGroup( injector: EnvironmentInjector, config: Route[], segmentGroup: UrlSegmentGroup, outlet: string, parentRoute: ActivatedRouteSnapshot, ): Observable<TreeNode<ActivatedRouteSnapshot>[]> { if (segmentGroup.segments.length === 0 && segmentGroup.hasChildren()) { return this.processChildren(injector, config, segmentGroup, parentRoute); } return this.processSegment( injector, config, segmentGroup, segmentGroup.segments, outlet, true, parentRoute, ).pipe(map((child) => (child instanceof TreeNode ? [child] : []))); } /** * Matches every child outlet in the `segmentGroup` to a `Route` in the config. Returns `null` if * we cannot find a match for _any_ of the children. * * @param config - The `Routes` to match against * @param segmentGroup - The `UrlSegmentGroup` whose children need to be matched against the * config. */ processChildren( injector: EnvironmentInjector, config: Route[], segmentGroup: UrlSegmentGroup, parentRoute: ActivatedRouteSnapshot, ): Observable<TreeNode<ActivatedRouteSnapshot>[]> { // Expand outlets one at a time, starting with the primary outlet. We need to do it this way // because an absolute redirect from the primary outlet takes precedence. const childOutlets: string[] = []; for (const child of Object.keys(segmentGroup.children)) { if (child === 'primary') { childOutlets.unshift(child); } else { childOutlets.push(child); } } return from(childOutlets).pipe( concatMap((childOutlet) => { const child = segmentGroup.children[childOutlet]; // Sort the config so that routes with outlets that match the one being activated // appear first, followed by routes for other outlets, which might match if they have // an empty path. const sortedConfig = sortByMatchingOutlets(config, childOutlet); return this.processSegmentGroup(injector, sortedConfig, child, childOutlet, parentRoute); }), scan((children, outletChildren) => { children.push(...outletChildren); return children; }), defaultIfEmpty(null as TreeNode<ActivatedRouteSnapshot>[] | null), last(), mergeMap((children) => { if (children === null) return noMatch(segmentGroup); // Because we may have matched two outlets to the same empty path segment, we can have // multiple activated results for the same outlet. We should merge the children of // these results so the final return value is only one `TreeNode` per outlet. const mergedChildren = mergeEmptyPathMatches(children); if (typeof ngDevMode === 'undefined' || ngDevMode) { // This should really never happen - we are only taking the first match for each // outlet and merge the empty path matches. checkOutletNameUniqueness(mergedChildren); } sortActivatedRouteSnapshots(mergedChildren); return of(mergedChildren); }), ); } processSegment( injector: EnvironmentInjector, routes: Route[], segmentGroup: UrlSegmentGroup, segments: UrlSegment[], outlet: string, allowRedirects: boolean, parentRoute: ActivatedRouteSnapshot, ): Observable<TreeNode<ActivatedRouteSnapshot> | NoLeftoversInUrl> { return from(routes).pipe( concatMap((r) => { return this.processSegmentAgainstRoute( r._injector ?? injector, routes, r, segmentGroup, segments, outlet, allowRedirects, parentRoute, ).pipe( catchError((e: any) => { if (e instanceof NoMatch) { return of(null); } throw e; }), ); }), first((x): x is TreeNode<ActivatedRouteSnapshot> | NoLeftoversInUrl => !!x), catchError((e) => { if (isEmptyError(e)) { if (noLeftoversInUrl(segmentGroup, segments, outlet)) { return of(new NoLeftoversInUrl()); } return noMatch(segmentGroup); } throw e; }), ); } processSegmentAgainstRoute( injector: EnvironmentInjector, routes: Route[], route: Route, rawSegment: UrlSegmentGroup, segments: UrlSegment[], outlet: string, allowRedirects: boolean, parentRoute: ActivatedRouteSnapshot, ): Observable<TreeNode<ActivatedRouteSnapshot> | NoLeftoversInUrl> { // We allow matches to empty paths when the outlets differ so we can match a url like `/(b:b)` to // a config like // * `{path: '', children: [{path: 'b', outlet: 'b'}]}` // or even // * `{path: '', outlet: 'a', children: [{path: 'b', outlet: 'b'}]` // // The exception here is when the segment outlet is for the primary outlet. This would // result in a match inside the named outlet because all children there are written as primary // outlets. So we need to prevent child named outlet matches in a url like `/b` in a config like // * `{path: '', outlet: 'x' children: [{path: 'b'}]}` // This should only match if the url is `/(x:b)`. if ( getOutlet(route) !== outlet && (outlet === PRIMARY_OUTLET || !emptyPathMatch(rawSegment, segments, route)) ) { return noMatch(rawSegment); } if (route.redirectTo === undefined) { return this.matchSegmentAgainstRoute( injector, rawSegment, route, segments, outlet, parentRoute, ); } if (this.allowRedirects && allowRedirects) { return this.expandSegmentAgainstRouteUsingRedirect( injector, rawSegment, routes, route, segments, outlet, parentRoute, ); } return noMatch(rawSegment); }
{ "end_byte": 11066, "start_byte": 2249, "url": "https://github.com/angular/angular/blob/main/packages/router/src/recognize.ts" }
angular/packages/router/src/recognize.ts_11070_20285
rivate expandSegmentAgainstRouteUsingRedirect( injector: EnvironmentInjector, segmentGroup: UrlSegmentGroup, routes: Route[], route: Route, segments: UrlSegment[], outlet: string, parentRoute: ActivatedRouteSnapshot, ): Observable<TreeNode<ActivatedRouteSnapshot> | NoLeftoversInUrl> { const {matched, parameters, consumedSegments, positionalParamSegments, remainingSegments} = match(segmentGroup, route, segments); if (!matched) return noMatch(segmentGroup); // TODO(atscott): Move all of this under an if(ngDevMode) as a breaking change and allow stack // size exceeded in production if (typeof route.redirectTo === 'string' && route.redirectTo[0] === '/') { this.absoluteRedirectCount++; if (this.absoluteRedirectCount > MAX_ALLOWED_REDIRECTS) { if (ngDevMode) { throw new RuntimeError( RuntimeErrorCode.INFINITE_REDIRECT, `Detected possible infinite redirect when redirecting from '${this.urlTree}' to '${route.redirectTo}'.\n` + `This is currently a dev mode only error but will become a` + ` call stack size exceeded error in production in a future major version.`, ); } this.allowRedirects = false; } } const currentSnapshot = new ActivatedRouteSnapshot( segments, parameters, Object.freeze({...this.urlTree.queryParams}), this.urlTree.fragment, getData(route), getOutlet(route), route.component ?? route._loadedComponent ?? null, route, getResolve(route), ); const inherited = getInherited(currentSnapshot, parentRoute, this.paramsInheritanceStrategy); currentSnapshot.params = Object.freeze(inherited.params); currentSnapshot.data = Object.freeze(inherited.data); const newTree = this.applyRedirects.applyRedirectCommands( consumedSegments, route.redirectTo!, positionalParamSegments, currentSnapshot, injector, ); return this.applyRedirects.lineralizeSegments(route, newTree).pipe( mergeMap((newSegments: UrlSegment[]) => { return this.processSegment( injector, routes, segmentGroup, newSegments.concat(remainingSegments), outlet, false, parentRoute, ); }), ); } matchSegmentAgainstRoute( injector: EnvironmentInjector, rawSegment: UrlSegmentGroup, route: Route, segments: UrlSegment[], outlet: string, parentRoute: ActivatedRouteSnapshot, ): Observable<TreeNode<ActivatedRouteSnapshot>> { const matchResult = matchWithChecks(rawSegment, route, segments, injector, this.urlSerializer); if (route.path === '**') { // Prior versions of the route matching algorithm would stop matching at the wildcard route. // We should investigate a better strategy for any existing children. Otherwise, these // child segments are silently dropped from the navigation. // https://github.com/angular/angular/issues/40089 rawSegment.children = {}; } return matchResult.pipe( switchMap((result) => { if (!result.matched) { return noMatch(rawSegment); } // If the route has an injector created from providers, we should start using that. injector = route._injector ?? injector; return this.getChildConfig(injector, route, segments).pipe( switchMap(({routes: childConfig}) => { const childInjector = route._loadedInjector ?? injector; const {parameters, consumedSegments, remainingSegments} = result; const snapshot = new ActivatedRouteSnapshot( consumedSegments, parameters, Object.freeze({...this.urlTree.queryParams}), this.urlTree.fragment, getData(route), getOutlet(route), route.component ?? route._loadedComponent ?? null, route, getResolve(route), ); const inherited = getInherited(snapshot, parentRoute, this.paramsInheritanceStrategy); snapshot.params = Object.freeze(inherited.params); snapshot.data = Object.freeze(inherited.data); const {segmentGroup, slicedSegments} = split( rawSegment, consumedSegments, remainingSegments, childConfig, ); if (slicedSegments.length === 0 && segmentGroup.hasChildren()) { return this.processChildren(childInjector, childConfig, segmentGroup, snapshot).pipe( map((children) => { return new TreeNode(snapshot, children); }), ); } if (childConfig.length === 0 && slicedSegments.length === 0) { return of(new TreeNode(snapshot, [])); } const matchedOnOutlet = getOutlet(route) === outlet; // If we matched a config due to empty path match on a different outlet, we need to // continue passing the current outlet for the segment rather than switch to PRIMARY. // Note that we switch to primary when we have a match because outlet configs look like // this: {path: 'a', outlet: 'a', children: [ // {path: 'b', component: B}, // {path: 'c', component: C}, // ]} // Notice that the children of the named outlet are configured with the primary outlet return this.processSegment( childInjector, childConfig, segmentGroup, slicedSegments, matchedOnOutlet ? PRIMARY_OUTLET : outlet, true, snapshot, ).pipe( map((child) => { return new TreeNode(snapshot, child instanceof TreeNode ? [child] : []); }), ); }), ); }), ); } private getChildConfig( injector: EnvironmentInjector, route: Route, segments: UrlSegment[], ): Observable<LoadedRouterConfig> { if (route.children) { // The children belong to the same module return of({routes: route.children, injector}); } if (route.loadChildren) { // lazy children belong to the loaded module if (route._loadedRoutes !== undefined) { return of({routes: route._loadedRoutes, injector: route._loadedInjector}); } return runCanLoadGuards(injector, route, segments, this.urlSerializer).pipe( mergeMap((shouldLoadResult: boolean) => { if (shouldLoadResult) { return this.configLoader.loadChildren(injector, route).pipe( tap((cfg: LoadedRouterConfig) => { route._loadedRoutes = cfg.routes; route._loadedInjector = cfg.injector; }), ); } return canLoadFails(route); }), ); } return of({routes: [], injector}); } } function sortActivatedRouteSnapshots(nodes: TreeNode<ActivatedRouteSnapshot>[]): void { nodes.sort((a, b) => { if (a.value.outlet === PRIMARY_OUTLET) return -1; if (b.value.outlet === PRIMARY_OUTLET) return 1; return a.value.outlet.localeCompare(b.value.outlet); }); } function hasEmptyPathConfig(node: TreeNode<ActivatedRouteSnapshot>) { const config = node.value.routeConfig; return config && config.path === ''; } /** * Finds `TreeNode`s with matching empty path route configs and merges them into `TreeNode` with * the children from each duplicate. This is necessary because different outlets can match a * single empty path route config and the results need to then be merged. */ function mergeEmptyPathMatches( nodes: Array<TreeNode<ActivatedRouteSnapshot>>, ): Array<TreeNode<ActivatedRouteSnapshot>> { const result: Array<TreeNode<ActivatedRouteSnapshot>> = []; // The set of nodes which contain children that were merged from two duplicate empty path nodes. const mergedNodes: Set<TreeNode<ActivatedRouteSnapshot>> = new Set(); for (const node of nodes) { if (!hasEmptyPathConfig(node)) { result.push(node); continue; } const duplicateEmptyPathNode = result.find( (resultNode) => node.value.routeConfig === resultNode.value.routeConfig, ); if (duplicateEmptyPathNode !== undefined) { duplicateEmptyPathNode.children.push(...node.children); mergedNodes.add(duplicateEmptyPathNode); } else { result.push(node); } } // For each node which has children from multiple sources, we need to recompute a new `TreeNode` // by also merging those children. This is necessary when there are multiple empty path configs // in a row. Put another way: whenever we combine children of two nodes, we need to also check // if any of those children can be combined into a single node as well. for (const mergedNode of mergedNodes) { const mergedChildren = mergeEmptyPathMatches(mergedNode.children); result.push(new TreeNode(mergedNode.value, mergedChildren)); } return result.filter((n) => !mergedNodes.has(n)); }
{ "end_byte": 20285, "start_byte": 11070, "url": "https://github.com/angular/angular/blob/main/packages/router/src/recognize.ts" }
angular/packages/router/src/recognize.ts_20287_21129
unction checkOutletNameUniqueness(nodes: TreeNode<ActivatedRouteSnapshot>[]): void { const names: {[k: string]: ActivatedRouteSnapshot} = {}; nodes.forEach((n) => { const routeWithSameOutletName = names[n.value.outlet]; if (routeWithSameOutletName) { const p = routeWithSameOutletName.url.map((s) => s.toString()).join('/'); const c = n.value.url.map((s) => s.toString()).join('/'); throw new RuntimeError( RuntimeErrorCode.TWO_SEGMENTS_WITH_SAME_OUTLET, (typeof ngDevMode === 'undefined' || ngDevMode) && `Two segments cannot have the same outlet name: '${p}' and '${c}'.`, ); } names[n.value.outlet] = n.value; }); } function getData(route: Route): Data { return route.data || {}; } function getResolve(route: Route): ResolveData { return route.resolve || {}; }
{ "end_byte": 21129, "start_byte": 20287, "url": "https://github.com/angular/angular/blob/main/packages/router/src/recognize.ts" }
angular/packages/router/src/provide_router.ts_0_8777
/** * @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.dev/license */ import { HashLocationStrategy, LOCATION_INITIALIZED, LocationStrategy, ViewportScroller, } from '@angular/common'; import { APP_BOOTSTRAP_LISTENER, APP_INITIALIZER, ApplicationRef, ComponentRef, ENVIRONMENT_INITIALIZER, EnvironmentProviders, inject, InjectFlags, InjectionToken, Injector, makeEnvironmentProviders, NgZone, Provider, runInInjectionContext, Type, } from '@angular/core'; import {of, Subject} from 'rxjs'; import {INPUT_BINDER, RoutedComponentInputBinder} from './directives/router_outlet'; import {Event, NavigationError, stringifyEvent} from './events'; import {RedirectCommand, Routes} from './models'; import {NAVIGATION_ERROR_HANDLER, NavigationTransitions} from './navigation_transition'; import {Router} from './router'; import {InMemoryScrollingOptions, ROUTER_CONFIGURATION, RouterConfigOptions} from './router_config'; import {ROUTES} from './router_config_loader'; import {PreloadingStrategy, RouterPreloader} from './router_preloader'; import {ROUTER_SCROLLER, RouterScroller} from './router_scroller'; import {ActivatedRoute} from './router_state'; import {UrlSerializer} from './url_tree'; import {afterNextNavigation} from './utils/navigations'; import { CREATE_VIEW_TRANSITION, createViewTransition, VIEW_TRANSITION_OPTIONS, ViewTransitionsFeatureOptions, } from './utils/view_transition'; /** * Sets up providers necessary to enable `Router` functionality for the application. * Allows to configure a set of routes as well as extra features that should be enabled. * * @usageNotes * * Basic example of how you can add a Router to your application: * ``` * const appRoutes: Routes = []; * bootstrapApplication(AppComponent, { * providers: [provideRouter(appRoutes)] * }); * ``` * * You can also enable optional features in the Router by adding functions from the `RouterFeatures` * type: * ``` * const appRoutes: Routes = []; * bootstrapApplication(AppComponent, * { * providers: [ * provideRouter(appRoutes, * withDebugTracing(), * withRouterConfig({paramsInheritanceStrategy: 'always'})) * ] * } * ); * ``` * * @see {@link RouterFeatures} * * @publicApi * @param routes A set of `Route`s to use for the application routing table. * @param features Optional features to configure additional router behaviors. * @returns A set of providers to setup a Router. */ export function provideRouter(routes: Routes, ...features: RouterFeatures[]): EnvironmentProviders { return makeEnvironmentProviders([ {provide: ROUTES, multi: true, useValue: routes}, typeof ngDevMode === 'undefined' || ngDevMode ? {provide: ROUTER_IS_PROVIDED, useValue: true} : [], {provide: ActivatedRoute, useFactory: rootRoute, deps: [Router]}, {provide: APP_BOOTSTRAP_LISTENER, multi: true, useFactory: getBootstrapListener}, features.map((feature) => feature.ɵproviders), ]); } export function rootRoute(router: Router): ActivatedRoute { return router.routerState.root; } /** * Helper type to represent a Router feature. * * @publicApi */ export interface RouterFeature<FeatureKind extends RouterFeatureKind> { ɵkind: FeatureKind; ɵproviders: Provider[]; } /** * Helper function to create an object that represents a Router feature. */ function routerFeature<FeatureKind extends RouterFeatureKind>( kind: FeatureKind, providers: Provider[], ): RouterFeature<FeatureKind> { return {ɵkind: kind, ɵproviders: providers}; } /** * An Injection token used to indicate whether `provideRouter` or `RouterModule.forRoot` was ever * called. */ export const ROUTER_IS_PROVIDED = new InjectionToken<boolean>('', { providedIn: 'root', factory: () => false, }); const routerIsProvidedDevModeCheck = { provide: ENVIRONMENT_INITIALIZER, multi: true, useFactory() { return () => { if (!inject(ROUTER_IS_PROVIDED)) { console.warn( '`provideRoutes` was called without `provideRouter` or `RouterModule.forRoot`. ' + 'This is likely a mistake.', ); } }; }, }; /** * Registers a DI provider for a set of routes. * @param routes The route configuration to provide. * * @usageNotes * * ``` * @NgModule({ * providers: [provideRoutes(ROUTES)] * }) * class LazyLoadedChildModule {} * ``` * * @deprecated If necessary, provide routes using the `ROUTES` `InjectionToken`. * @see {@link ROUTES} * @publicApi */ export function provideRoutes(routes: Routes): Provider[] { return [ {provide: ROUTES, multi: true, useValue: routes}, typeof ngDevMode === 'undefined' || ngDevMode ? routerIsProvidedDevModeCheck : [], ]; } /** * A type alias for providers returned by `withInMemoryScrolling` for use with `provideRouter`. * * @see {@link withInMemoryScrolling} * @see {@link provideRouter} * * @publicApi */ export type InMemoryScrollingFeature = RouterFeature<RouterFeatureKind.InMemoryScrollingFeature>; /** * Enables customizable scrolling behavior for router navigations. * * @usageNotes * * Basic example of how you can enable scrolling feature: * ``` * const appRoutes: Routes = []; * bootstrapApplication(AppComponent, * { * providers: [ * provideRouter(appRoutes, withInMemoryScrolling()) * ] * } * ); * ``` * * @see {@link provideRouter} * @see {@link ViewportScroller} * * @publicApi * @param options Set of configuration parameters to customize scrolling behavior, see * `InMemoryScrollingOptions` for additional information. * @returns A set of providers for use with `provideRouter`. */ export function withInMemoryScrolling( options: InMemoryScrollingOptions = {}, ): InMemoryScrollingFeature { const providers = [ { provide: ROUTER_SCROLLER, useFactory: () => { const viewportScroller = inject(ViewportScroller); const zone = inject(NgZone); const transitions = inject(NavigationTransitions); const urlSerializer = inject(UrlSerializer); return new RouterScroller(urlSerializer, transitions, viewportScroller, zone, options); }, }, ]; return routerFeature(RouterFeatureKind.InMemoryScrollingFeature, providers); } export function getBootstrapListener() { const injector = inject(Injector); return (bootstrappedComponentRef: ComponentRef<unknown>) => { const ref = injector.get(ApplicationRef); if (bootstrappedComponentRef !== ref.components[0]) { return; } const router = injector.get(Router); const bootstrapDone = injector.get(BOOTSTRAP_DONE); if (injector.get(INITIAL_NAVIGATION) === InitialNavigation.EnabledNonBlocking) { router.initialNavigation(); } injector.get(ROUTER_PRELOADER, null, InjectFlags.Optional)?.setUpPreloading(); injector.get(ROUTER_SCROLLER, null, InjectFlags.Optional)?.init(); router.resetRootComponentType(ref.componentTypes[0]); if (!bootstrapDone.closed) { bootstrapDone.next(); bootstrapDone.complete(); bootstrapDone.unsubscribe(); } }; } /** * A subject used to indicate that the bootstrapping phase is done. When initial navigation is * `enabledBlocking`, the first navigation waits until bootstrapping is finished before continuing * to the activation phase. */ const BOOTSTRAP_DONE = new InjectionToken<Subject<void>>( typeof ngDevMode === 'undefined' || ngDevMode ? 'bootstrap done indicator' : '', { factory: () => { return new Subject<void>(); }, }, ); /** * This and the INITIAL_NAVIGATION token are used internally only. The public API side of this is * configured through the `ExtraOptions`. * * When set to `EnabledBlocking`, the initial navigation starts before the root * component is created. The bootstrap is blocked until the initial navigation is complete. This * value should be set in case you use [server-side rendering](guide/ssr), but do not enable * [hydration](guide/hydration) for your application. * * When set to `EnabledNonBlocking`, the initial navigation starts after the root component has been * created. The bootstrap is not blocked on the completion of the initial navigation. * * When set to `Disabled`, the initial navigation is not performed. The location listener is set up * before the root component gets created. Use if there is a reason to have more control over when * the router starts its initial navigation due to some complex initialization logic. * * @see {@link ExtraOptions} */ const enum InitialNavigation { EnabledBlocking, EnabledNonBlocking, Disabled, } con
{ "end_byte": 8777, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/router/src/provide_router.ts" }
angular/packages/router/src/provide_router.ts_8779_18032
INITIAL_NAVIGATION = new InjectionToken<InitialNavigation>( typeof ngDevMode === 'undefined' || ngDevMode ? 'initial navigation' : '', {providedIn: 'root', factory: () => InitialNavigation.EnabledNonBlocking}, ); /** * A type alias for providers returned by `withEnabledBlockingInitialNavigation` for use with * `provideRouter`. * * @see {@link withEnabledBlockingInitialNavigation} * @see {@link provideRouter} * * @publicApi */ export type EnabledBlockingInitialNavigationFeature = RouterFeature<RouterFeatureKind.EnabledBlockingInitialNavigationFeature>; /** * A type alias for providers returned by `withEnabledBlockingInitialNavigation` or * `withDisabledInitialNavigation` functions for use with `provideRouter`. * * @see {@link withEnabledBlockingInitialNavigation} * @see {@link withDisabledInitialNavigation} * @see {@link provideRouter} * * @publicApi */ export type InitialNavigationFeature = | EnabledBlockingInitialNavigationFeature | DisabledInitialNavigationFeature; /** * Configures initial navigation to start before the root component is created. * * The bootstrap is blocked until the initial navigation is complete. This should be set in case * you use [server-side rendering](guide/ssr), but do not enable [hydration](guide/hydration) for * your application. * * @usageNotes * * Basic example of how you can enable this navigation behavior: * ``` * const appRoutes: Routes = []; * bootstrapApplication(AppComponent, * { * providers: [ * provideRouter(appRoutes, withEnabledBlockingInitialNavigation()) * ] * } * ); * ``` * * @see {@link provideRouter} * * @publicApi * @returns A set of providers for use with `provideRouter`. */ export function withEnabledBlockingInitialNavigation(): EnabledBlockingInitialNavigationFeature { const providers = [ {provide: INITIAL_NAVIGATION, useValue: InitialNavigation.EnabledBlocking}, { provide: APP_INITIALIZER, multi: true, deps: [Injector], useFactory: (injector: Injector) => { const locationInitialized: Promise<any> = injector.get( LOCATION_INITIALIZED, Promise.resolve(), ); return () => { return locationInitialized.then(() => { return new Promise((resolve) => { const router = injector.get(Router); const bootstrapDone = injector.get(BOOTSTRAP_DONE); afterNextNavigation(router, () => { // Unblock APP_INITIALIZER in case the initial navigation was canceled or errored // without a redirect. resolve(true); }); injector.get(NavigationTransitions).afterPreactivation = () => { // Unblock APP_INITIALIZER once we get to `afterPreactivation`. At this point, we // assume activation will complete successfully (even though this is not // guaranteed). resolve(true); return bootstrapDone.closed ? of(void 0) : bootstrapDone; }; router.initialNavigation(); }); }); }; }, }, ]; return routerFeature(RouterFeatureKind.EnabledBlockingInitialNavigationFeature, providers); } /** * A type alias for providers returned by `withDisabledInitialNavigation` for use with * `provideRouter`. * * @see {@link withDisabledInitialNavigation} * @see {@link provideRouter} * * @publicApi */ export type DisabledInitialNavigationFeature = RouterFeature<RouterFeatureKind.DisabledInitialNavigationFeature>; /** * Disables initial navigation. * * Use if there is a reason to have more control over when the router starts its initial navigation * due to some complex initialization logic. * * @usageNotes * * Basic example of how you can disable initial navigation: * ``` * const appRoutes: Routes = []; * bootstrapApplication(AppComponent, * { * providers: [ * provideRouter(appRoutes, withDisabledInitialNavigation()) * ] * } * ); * ``` * * @see {@link provideRouter} * * @returns A set of providers for use with `provideRouter`. * * @publicApi */ export function withDisabledInitialNavigation(): DisabledInitialNavigationFeature { const providers = [ { provide: APP_INITIALIZER, multi: true, useFactory: () => { const router = inject(Router); return () => { router.setUpLocationChangeListener(); }; }, }, {provide: INITIAL_NAVIGATION, useValue: InitialNavigation.Disabled}, ]; return routerFeature(RouterFeatureKind.DisabledInitialNavigationFeature, providers); } /** * A type alias for providers returned by `withDebugTracing` for use with `provideRouter`. * * @see {@link withDebugTracing} * @see {@link provideRouter} * * @publicApi */ export type DebugTracingFeature = RouterFeature<RouterFeatureKind.DebugTracingFeature>; /** * Enables logging of all internal navigation events to the console. * Extra logging might be useful for debugging purposes to inspect Router event sequence. * * @usageNotes * * Basic example of how you can enable debug tracing: * ``` * const appRoutes: Routes = []; * bootstrapApplication(AppComponent, * { * providers: [ * provideRouter(appRoutes, withDebugTracing()) * ] * } * ); * ``` * * @see {@link provideRouter} * * @returns A set of providers for use with `provideRouter`. * * @publicApi */ export function withDebugTracing(): DebugTracingFeature { let providers: Provider[] = []; if (typeof ngDevMode === 'undefined' || ngDevMode) { providers = [ { provide: ENVIRONMENT_INITIALIZER, multi: true, useFactory: () => { const router = inject(Router); return () => router.events.subscribe((e: Event) => { // tslint:disable:no-console console.group?.(`Router Event: ${(<any>e.constructor).name}`); console.log(stringifyEvent(e)); console.log(e); console.groupEnd?.(); // tslint:enable:no-console }); }, }, ]; } else { providers = []; } return routerFeature(RouterFeatureKind.DebugTracingFeature, providers); } const ROUTER_PRELOADER = new InjectionToken<RouterPreloader>( typeof ngDevMode === 'undefined' || ngDevMode ? 'router preloader' : '', ); /** * A type alias that represents a feature which enables preloading in Router. * The type is used to describe the return value of the `withPreloading` function. * * @see {@link withPreloading} * @see {@link provideRouter} * * @publicApi */ export type PreloadingFeature = RouterFeature<RouterFeatureKind.PreloadingFeature>; /** * Allows to configure a preloading strategy to use. The strategy is configured by providing a * reference to a class that implements a `PreloadingStrategy`. * * @usageNotes * * Basic example of how you can configure preloading: * ``` * const appRoutes: Routes = []; * bootstrapApplication(AppComponent, * { * providers: [ * provideRouter(appRoutes, withPreloading(PreloadAllModules)) * ] * } * ); * ``` * * @see {@link provideRouter} * * @param preloadingStrategy A reference to a class that implements a `PreloadingStrategy` that * should be used. * @returns A set of providers for use with `provideRouter`. * * @publicApi */ export function withPreloading(preloadingStrategy: Type<PreloadingStrategy>): PreloadingFeature { const providers = [ {provide: ROUTER_PRELOADER, useExisting: RouterPreloader}, {provide: PreloadingStrategy, useExisting: preloadingStrategy}, ]; return routerFeature(RouterFeatureKind.PreloadingFeature, providers); } /** * A type alias for providers returned by `withRouterConfig` for use with `provideRouter`. * * @see {@link withRouterConfig} * @see {@link provideRouter} * * @publicApi */ export type RouterConfigurationFeature = RouterFeature<RouterFeatureKind.RouterConfigurationFeature>; /** * Allows to provide extra parameters to configure Router. * * @usageNotes * * Basic example of how you can provide extra configuration options: * ``` * const appRoutes: Routes = []; * bootstrapApplication(AppComponent, * { * providers: [ * provideRouter(appRoutes, withRouterConfig({ * onSameUrlNavigation: 'reload' * })) * ] * } * ); * ``` * * @see {@link provideRouter} * * @param options A set of parameters to configure Router, see `RouterConfigOptions` for * additional information. * @returns A set of providers for use with `provideRouter`. * * @publicApi */ export function withRouterConfig(options: RouterConfigOptions): RouterConfigurationFeature { const providers = [{provide: ROUTER_CONFIGURATION, useValue: options}]; return routerFeature(RouterFeatureKind.RouterConfigurationFeature, providers); } /** * A type alias for providers returned by `withHashLocation` for use with `provideRouter`. * * @see {@link withHashLocation} * @see {@link provideRouter} * * @publicApi */ export type RouterHashLocationFeature = RouterFeature<RouterFeatureKind.RouterHashLocationFeature>; /**
{ "end_byte": 18032, "start_byte": 8779, "url": "https://github.com/angular/angular/blob/main/packages/router/src/provide_router.ts" }
angular/packages/router/src/provide_router.ts_18034_25289
* Provides the location strategy that uses the URL fragment instead of the history API. * * @usageNotes * * Basic example of how you can use the hash location option: * ``` * const appRoutes: Routes = []; * bootstrapApplication(AppComponent, * { * providers: [ * provideRouter(appRoutes, withHashLocation()) * ] * } * ); * ``` * * @see {@link provideRouter} * @see {@link HashLocationStrategy} * * @returns A set of providers for use with `provideRouter`. * * @publicApi */ export function withHashLocation(): RouterHashLocationFeature { const providers = [{provide: LocationStrategy, useClass: HashLocationStrategy}]; return routerFeature(RouterFeatureKind.RouterHashLocationFeature, providers); } /** * A type alias for providers returned by `withNavigationErrorHandler` for use with `provideRouter`. * * @see {@link withNavigationErrorHandler} * @see {@link provideRouter} * * @publicApi */ export type NavigationErrorHandlerFeature = RouterFeature<RouterFeatureKind.NavigationErrorHandlerFeature>; /** * Provides a function which is called when a navigation error occurs. * * This function is run inside application's [injection context](guide/di/dependency-injection-context) * so you can use the [`inject`](api/core/inject) function. * * This function can return a `RedirectCommand` to convert the error to a redirect, similar to returning * a `UrlTree` or `RedirectCommand` from a guard. This will also prevent the `Router` from emitting * `NavigationError`; it will instead emit `NavigationCancel` with code NavigationCancellationCode.Redirect. * Return values other than `RedirectCommand` are ignored and do not change any behavior with respect to * how the `Router` handles the error. * * @usageNotes * * Basic example of how you can use the error handler option: * ``` * const appRoutes: Routes = []; * bootstrapApplication(AppComponent, * { * providers: [ * provideRouter(appRoutes, withNavigationErrorHandler((e: NavigationError) => * inject(MyErrorTracker).trackError(e))) * ] * } * ); * ``` * * @see {@link NavigationError} * @see {@link core/inject} * @see {@link runInInjectionContext} * * @returns A set of providers for use with `provideRouter`. * * @publicApi */ export function withNavigationErrorHandler( handler: (error: NavigationError) => unknown | RedirectCommand, ): NavigationErrorHandlerFeature { const providers = [ { provide: NAVIGATION_ERROR_HANDLER, useValue: handler, }, ]; return routerFeature(RouterFeatureKind.NavigationErrorHandlerFeature, providers); } /** * A type alias for providers returned by `withComponentInputBinding` for use with `provideRouter`. * * @see {@link withComponentInputBinding} * @see {@link provideRouter} * * @publicApi */ export type ComponentInputBindingFeature = RouterFeature<RouterFeatureKind.ComponentInputBindingFeature>; /** * A type alias for providers returned by `withViewTransitions` for use with `provideRouter`. * * @see {@link withViewTransitions} * @see {@link provideRouter} * * @publicApi */ export type ViewTransitionsFeature = RouterFeature<RouterFeatureKind.ViewTransitionsFeature>; /** * Enables binding information from the `Router` state directly to the inputs of the component in * `Route` configurations. * * @usageNotes * * Basic example of how you can enable the feature: * ``` * const appRoutes: Routes = []; * bootstrapApplication(AppComponent, * { * providers: [ * provideRouter(appRoutes, withComponentInputBinding()) * ] * } * ); * ``` * * The router bindings information from any of the following sources: * * - query parameters * - path and matrix parameters * - static route data * - data from resolvers * * Duplicate keys are resolved in the same order from above, from least to greatest, * meaning that resolvers have the highest precedence and override any of the other information * from the route. * * Importantly, when an input does not have an item in the route data with a matching key, this * input is set to `undefined`. This prevents previous information from being * retained if the data got removed from the route (i.e. if a query parameter is removed). * Default values can be provided with a resolver on the route to ensure the value is always present * or an input and use an input transform in the component. * * @see {@link guide/components/inputs#input-transforms input transforms} * @returns A set of providers for use with `provideRouter`. */ export function withComponentInputBinding(): ComponentInputBindingFeature { const providers = [ RoutedComponentInputBinder, {provide: INPUT_BINDER, useExisting: RoutedComponentInputBinder}, ]; return routerFeature(RouterFeatureKind.ComponentInputBindingFeature, providers); } /** * Enables view transitions in the Router by running the route activation and deactivation inside of * `document.startViewTransition`. * * Note: The View Transitions API is not available in all browsers. If the browser does not support * view transitions, the Router will not attempt to start a view transition and continue processing * the navigation as usual. * * @usageNotes * * Basic example of how you can enable the feature: * ``` * const appRoutes: Routes = []; * bootstrapApplication(AppComponent, * { * providers: [ * provideRouter(appRoutes, withViewTransitions()) * ] * } * ); * ``` * * @returns A set of providers for use with `provideRouter`. * @see https://developer.chrome.com/docs/web-platform/view-transitions/ * @see https://developer.mozilla.org/en-US/docs/Web/API/View_Transitions_API * @developerPreview */ export function withViewTransitions( options?: ViewTransitionsFeatureOptions, ): ViewTransitionsFeature { const providers = [ {provide: CREATE_VIEW_TRANSITION, useValue: createViewTransition}, { provide: VIEW_TRANSITION_OPTIONS, useValue: {skipNextTransition: !!options?.skipInitialTransition, ...options}, }, ]; return routerFeature(RouterFeatureKind.ViewTransitionsFeature, providers); } /** * A type alias that represents all Router features available for use with `provideRouter`. * Features can be enabled by adding special functions to the `provideRouter` call. * See documentation for each symbol to find corresponding function name. See also `provideRouter` * documentation on how to use those functions. * * @see {@link provideRouter} * * @publicApi */ export type RouterFeatures = | PreloadingFeature | DebugTracingFeature | InitialNavigationFeature | InMemoryScrollingFeature | RouterConfigurationFeature | NavigationErrorHandlerFeature | ComponentInputBindingFeature | ViewTransitionsFeature | RouterHashLocationFeature; /** * The list of features as an enum to uniquely type each feature. */ export const enum RouterFeatureKind { PreloadingFeature, DebugTracingFeature, EnabledBlockingInitialNavigationFeature, DisabledInitialNavigationFeature, InMemoryScrollingFeature, RouterConfigurationFeature, RouterHashLocationFeature, NavigationErrorHandlerFeature, ComponentInputBindingFeature, ViewTransitionsFeature, }
{ "end_byte": 25289, "start_byte": 18034, "url": "https://github.com/angular/angular/blob/main/packages/router/src/provide_router.ts" }
angular/packages/router/src/private_export.ts_0_569
/** * @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.dev/license */ export {ɵEmptyOutletComponent} from './components/empty_outlet'; export {RestoredState as ɵRestoredState} from './navigation_transition'; export {loadChildren as ɵloadChildren} from './router_config_loader'; export {ROUTER_PROVIDERS as ɵROUTER_PROVIDERS} from './router_module'; export {afterNextNavigation as ɵafterNextNavigation} from './utils/navigations';
{ "end_byte": 569, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/router/src/private_export.ts" }
angular/packages/router/src/navigation_transition.ts_0_7642
/** * @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.dev/license */ import {Location} from '@angular/common'; import { EnvironmentInjector, inject, Injectable, InjectionToken, runInInjectionContext, Type, } from '@angular/core'; import {BehaviorSubject, combineLatest, EMPTY, from, Observable, of, Subject} from 'rxjs'; import { catchError, defaultIfEmpty, filter, finalize, map, switchMap, take, takeUntil, tap, } from 'rxjs/operators'; import {createRouterState} from './create_router_state'; import {INPUT_BINDER} from './directives/router_outlet'; import { BeforeActivateRoutes, Event, GuardsCheckEnd, GuardsCheckStart, IMPERATIVE_NAVIGATION, NavigationCancel, NavigationCancellationCode, NavigationEnd, NavigationError, NavigationSkipped, NavigationSkippedCode, NavigationStart, NavigationTrigger, RedirectRequest, ResolveEnd, ResolveStart, RouteConfigLoadEnd, RouteConfigLoadStart, RoutesRecognized, } from './events'; import { GuardResult, NavigationBehaviorOptions, QueryParamsHandling, RedirectCommand, Route, Routes, } from './models'; import { isNavigationCancelingError, isRedirectingNavigationCancelingError, redirectingNavigationError, } from './navigation_canceling_error'; import {activateRoutes} from './operators/activate_routes'; import {checkGuards} from './operators/check_guards'; import {recognize} from './operators/recognize'; import {resolveData} from './operators/resolve_data'; import {switchTap} from './operators/switch_tap'; import {TitleStrategy} from './page_title_strategy'; import {RouteReuseStrategy} from './route_reuse_strategy'; import {ROUTER_CONFIGURATION} from './router_config'; import {RouterConfigLoader} from './router_config_loader'; import {ChildrenOutletContexts} from './router_outlet_context'; import { ActivatedRoute, ActivatedRouteSnapshot, createEmptyState, RouterState, RouterStateSnapshot, } from './router_state'; import {Params} from './shared'; import {UrlHandlingStrategy} from './url_handling_strategy'; import {isUrlTree, UrlSerializer, UrlTree} from './url_tree'; import {Checks, getAllRouteGuards} from './utils/preactivation'; import {CREATE_VIEW_TRANSITION} from './utils/view_transition'; /** * @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 {@link Router#navigate} * @see {@link Router#createUrlTree} * @see [Routing and Navigation guide](guide/routing/common-router-tasks) * * @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() { * 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 * router.navigate(['/results'], { queryParams: { page: 1 } }); * ``` */ queryParams?: Params | null; /** * Sets the hash fragment for the URL. * * ``` * // Navigate to /results#top * 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 * 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 * 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 * 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 target URL should be constructed or interpreted. * * @see {@link Router#navigate} * @see {@link Router#navigateByUrl} * @see {@link Router#createurltree} * @see [Routing and Navigation guide](guide/routing/common-router-tasks) * @see {@link UrlCreationOptions} * @see {@link NavigationBehaviorOptions} * * @publicApi */ export interface NavigationExtras extends UrlCreationOptions, NavigationBehaviorOptions {} 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 */ exp
{ "end_byte": 7642, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/router/src/navigation_transition.ts" }
angular/packages/router/src/navigation_transition.ts_7643_14860
rt 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: UrlTree; /** * The initial target URL after being parsed with `UrlHandlingStrategy.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; /** * `UrlTree` to use when updating the browser URL for the navigation when `extras.browserUrl` is * defined. * @internal */ readonly targetBrowserUrl?: UrlTree | string; /** * TODO(atscott): If we want to make StateManager public, they will need access to this. Note that * it's already eventually exposed through router.routerState. * @internal */ targetRouterState?: RouterState; /** * 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 interface NavigationTransition { id: number; currentUrlTree: UrlTree; extractedUrl: UrlTree; currentRawUrl: UrlTree; urlAfterRedirects?: UrlTree; rawUrl: UrlTree; extras: NavigationExtras; resolve: (value: boolean | PromiseLike<boolean>) => void; reject: (reason?: any) => void; promise: Promise<boolean>; source: NavigationTrigger; restoredState: RestoredState | null; currentSnapshot: RouterStateSnapshot; targetSnapshot: RouterStateSnapshot | null; currentRouterState: RouterState; targetRouterState: RouterState | null; guards: Checks; guardsResult: GuardResult | null; } /** * The interface from the Router needed by the transitions. Used to avoid a circular dependency on * Router. This interface should be whittled down with future refactors. For example, we do not need * to get `UrlSerializer` from the Router. We can instead inject it in `NavigationTransitions` * directly. */ interface InternalRouterInterface { config: Routes; navigated: boolean; routeReuseStrategy: RouteReuseStrategy; onSameUrlNavigation: 'reload' | 'ignore'; } export const NAVIGATION_ERROR_HANDLER = new InjectionToken< (error: NavigationError) => unknown | RedirectCommand >(typeof ngDevMode === 'undefined' || ngDevMode ? 'navigation error handler' : ''); @Injectable({providedIn: 'root'}) export class NavigationTransitions { currentNavigation: Navigation | null = null; currentTransition: NavigationTransition | null = null; lastSuccessfulNavigation: Navigation | null = null; /** * These events are used to communicate back to the Router about the state of the transition. The * Router wants to respond to these events in various ways. Because the `NavigationTransition` * class is not public, this event subject is not publicly exposed. */ readonly events = new Subject<Event | BeforeActivateRoutes | RedirectRequest>(); /** * Used to abort the current transition with an error. */ readonly transitionAbortSubject = new Subject<Error>(); private readonly configLoader = inject(RouterConfigLoader); private readonly environmentInjector = inject(EnvironmentInjector); private readonly urlSerializer = inject(UrlSerializer); private readonly rootContexts = inject(ChildrenOutletContexts); private readonly location = inject(Location); private readonly inputBindingEnabled = inject(INPUT_BINDER, {optional: true}) !== null; private readonly titleStrategy?: TitleStrategy = inject(TitleStrategy); private readonly options = inject(ROUTER_CONFIGURATION, {optional: true}) || {}; private readonly paramsInheritanceStrategy = this.options.paramsInheritanceStrategy || 'emptyOnly'; private readonly urlHandlingStrategy = inject(UrlHandlingStrategy); private readonly createViewTransition = inject(CREATE_VIEW_TRANSITION, {optional: true}); private readonly navigationErrorHandler = inject(NAVIGATION_ERROR_HANDLER, {optional: true}); navigationId = 0; get hasRequestedNavigation() { return this.navigationId !== 0; } private transitions?: BehaviorSubject<NavigationTransition>; /** * Hook that enables you to pause navigation after the preactivation phase. * Used by `RouterModule`. * * @internal */ afterPreactivation: () => Observable<void> = () => of(void 0); /** @internal */ rootComponentType: Type<any> | null = null; constructor() { const onLoadStart = (r: Route) => this.events.next(new RouteConfigLoadStart(r)); const onLoadEnd = (r: Route) => this.events.next(new RouteConfigLoadEnd(r)); this.configLoader.onLoadEndListener = onLoadEnd; this.configLoader.onLoadStartListener = onLoadStart; } complete() { this.transitions?.complete(); } handleNavigationRequest( request: Pick< NavigationTransition, | 'source' | 'restoredState' | 'currentUrlTree' | 'currentRawUrl' | 'rawUrl' | 'extras' | 'resolve' | 'reject' | 'promise' | 'currentSnapshot' | 'currentRouterState' >, ) { const id = ++this.navigationId; this.transitions?.next({...this.transitions.value, ...request, id}); } setupNavigations( router: InternalRouterInterface, initialUrlTree: UrlTree, initialRouterState: RouterState, ): Observable<NavigationTransition> { this.transitions = new BehaviorSubject<NavigationTransition>({ id: 0, currentUrlTree: initialUrlTree, currentRawUrl: initialUrlTree, extractedUrl: this.urlHandlingStrategy.extract(initialUrlTree), urlAfterRedirects: this.urlHandlingStrategy.extract(initialUrlTree), rawUrl: initialUrlTree, extras: {}, resolve: () => {}, reject: () => {}, promise: Promise.resolve(true), source: IMPERATIVE_NAVIGATION, restoredState: null, currentSnapshot: initialRouterState.snapshot, targetSnapshot: null, currentRouterState: initialRouterState, targetRouterState: null, guards: {canActivateChecks: [], canDeactivateChecks: []}, guardsResult: null, }); return this.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
{ "end_byte": 14860, "start_byte": 7643, "url": "https://github.com/angular/angular/blob/main/packages/router/src/navigation_transition.ts" }
angular/packages/router/src/navigation_transition.ts_14867_26400
chMap((overallTransitionState) => { let completed = false; let errored = false; return of(overallTransitionState).pipe( switchMap((t) => { // It is possible that `switchMap` fails to cancel previous navigations if a new one happens synchronously while the operator // is processing the `next` notification of that previous navigation. This can happen when a new navigation (say 2) cancels a // previous one (1) and yet another navigation (3) happens synchronously in response to the `NavigationCancel` event for (1). // https://github.com/ReactiveX/rxjs/issues/7455 if (this.navigationId > overallTransitionState.id) { const cancellationReason = typeof ngDevMode === 'undefined' || ngDevMode ? `Navigation ID ${overallTransitionState.id} is not equal to the current navigation id ${this.navigationId}` : ''; this.cancelNavigationTransition( overallTransitionState, cancellationReason, NavigationCancellationCode.SupersededByNewNavigation, ); return EMPTY; } this.currentTransition = overallTransitionState; // Store the Navigation object this.currentNavigation = { id: t.id, initialUrl: t.rawUrl, extractedUrl: t.extractedUrl, targetBrowserUrl: typeof t.extras.browserUrl === 'string' ? this.urlSerializer.parse(t.extras.browserUrl) : t.extras.browserUrl, trigger: t.source, extras: t.extras, previousNavigation: !this.lastSuccessfulNavigation ? null : { ...this.lastSuccessfulNavigation, previousNavigation: null, }, }; const urlTransition = !router.navigated || this.isUpdatingInternalState() || this.isUpdatedBrowserUrl(); const onSameUrlNavigation = t.extras.onSameUrlNavigation ?? router.onSameUrlNavigation; if (!urlTransition && onSameUrlNavigation !== 'reload') { const reason = typeof ngDevMode === 'undefined' || ngDevMode ? `Navigation to ${t.rawUrl} was ignored because it is the same as the current Router URL.` : ''; this.events.next( new NavigationSkipped( t.id, this.urlSerializer.serialize(t.rawUrl), reason, NavigationSkippedCode.IgnoredSameUrlNavigation, ), ); t.resolve(false); return EMPTY; } if (this.urlHandlingStrategy.shouldProcessUrl(t.rawUrl)) { return of(t).pipe( // Fire NavigationStart event switchMap((t) => { const transition = this.transitions?.getValue(); this.events.next( new NavigationStart( t.id, this.urlSerializer.serialize(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); }), // Recognize recognize( this.environmentInjector, this.configLoader, this.rootComponentType, router.config, this.urlSerializer, this.paramsInheritanceStrategy, ), // Update URL if in `eager` update mode tap((t) => { overallTransitionState.targetSnapshot = t.targetSnapshot; overallTransitionState.urlAfterRedirects = t.urlAfterRedirects; this.currentNavigation = { ...this.currentNavigation!, finalUrl: t.urlAfterRedirects, }; // Fire RoutesRecognized const routesRecognized = new RoutesRecognized( t.id, this.urlSerializer.serialize(t.extractedUrl), this.urlSerializer.serialize(t.urlAfterRedirects!), t.targetSnapshot!, ); this.events.next(routesRecognized); }), ); } else if ( urlTransition && this.urlHandlingStrategy.shouldProcessUrl(t.currentRawUrl) ) { /* 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.*/ const {id, extractedUrl, source, restoredState, extras} = t; const navStart = new NavigationStart( id, this.urlSerializer.serialize(extractedUrl), source, restoredState, ); this.events.next(navStart); const targetSnapshot = createEmptyState(this.rootComponentType).snapshot; this.currentTransition = overallTransitionState = { ...t, targetSnapshot, urlAfterRedirects: extractedUrl, extras: {...extras, skipLocationChange: false, replaceUrl: false}, }; this.currentNavigation!.finalUrl = extractedUrl; return of(overallTransitionState); } 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. */ const reason = typeof ngDevMode === 'undefined' || ngDevMode ? `Navigation was ignored because the UrlHandlingStrategy` + ` indicated neither the current URL ${t.currentRawUrl} nor target URL ${t.rawUrl} should be processed.` : ''; this.events.next( new NavigationSkipped( t.id, this.urlSerializer.serialize(t.extractedUrl), reason, NavigationSkippedCode.IgnoredByUrlHandlingStrategy, ), ); t.resolve(false); return EMPTY; } }), // --- GUARDS --- tap((t) => { const guardsStart = new GuardsCheckStart( t.id, this.urlSerializer.serialize(t.extractedUrl), this.urlSerializer.serialize(t.urlAfterRedirects!), t.targetSnapshot!, ); this.events.next(guardsStart); }), map((t) => { this.currentTransition = overallTransitionState = { ...t, guards: getAllRouteGuards(t.targetSnapshot!, t.currentSnapshot, this.rootContexts), }; return overallTransitionState; }), checkGuards(this.environmentInjector, (evt: Event) => this.events.next(evt)), tap((t) => { overallTransitionState.guardsResult = t.guardsResult; if (t.guardsResult && typeof t.guardsResult !== 'boolean') { throw redirectingNavigationError(this.urlSerializer, t.guardsResult); } const guardsEnd = new GuardsCheckEnd( t.id, this.urlSerializer.serialize(t.extractedUrl), this.urlSerializer.serialize(t.urlAfterRedirects!), t.targetSnapshot!, !!t.guardsResult, ); this.events.next(guardsEnd); }), filter((t) => { if (!t.guardsResult) { this.cancelNavigationTransition(t, '', NavigationCancellationCode.GuardRejected); 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.urlSerializer.serialize(t.extractedUrl), this.urlSerializer.serialize(t.urlAfterRedirects!), t.targetSnapshot!, ); this.events.next(resolveStart); }), switchMap((t) => { let dataResolved = false; return of(t).pipe( resolveData(this.paramsInheritanceStrategy, this.environmentInjector), tap({ next: () => (dataResolved = true), complete: () => { if (!dataResolved) { this.cancelNavigationTransition( t, typeof ngDevMode === 'undefined' || ngDevMode ? `At least one route resolver didn't emit any value.` : '', NavigationCancellationCode.NoDataFromResolver, ); } }, }), ); }), tap((t) => { const resolveEnd = new ResolveEnd( t.id, this.urlSerializer.serialize(t.extractedUrl), this.urlSerializer.serialize(t.urlAfterRedirects!), t.targetSnapshot!, ); this.events.next(resolveEnd); }), ); } return undefined; }), // --- LOAD COMPONENTS --- switchTap((t: NavigationTransition) => { const loadComponents = (route: ActivatedRouteSnapshot): Array<Observable<void>> => { const loaders: Array<Observable<void>> = []; if (route.routeConfig?.loadComponent && !route.routeConfig._loadedComponent) { loaders.push( this.configLoader.loadComponent(route.routeConfig).pipe( tap((loadedComponent) => { route.component = loadedComponent; }), map(() => void 0), ), ); } for (const child of route.children) { loaders.push(...loadComponents(child)); } return loaders; }; return combineLatest(loadComponents(t.targetSnapshot!.root)).pipe( defaultIfEmpty(null), take(1), ); }), switchTap(() => this.afterPreactivation()),
{ "end_byte": 26400, "start_byte": 14867, "url": "https://github.com/angular/angular/blob/main/packages/router/src/navigation_transition.ts" }
angular/packages/router/src/navigation_transition.ts_26412_36442
chMap(() => { const {currentSnapshot, targetSnapshot} = overallTransitionState; const viewTransitionStarted = this.createViewTransition?.( this.environmentInjector, currentSnapshot.root, targetSnapshot!.root, ); // If view transitions are enabled, block the navigation until the view // transition callback starts. Otherwise, continue immediately. return viewTransitionStarted ? from(viewTransitionStarted).pipe(map(() => overallTransitionState)) : of(overallTransitionState); }), map((t: NavigationTransition) => { const targetRouterState = createRouterState( router.routeReuseStrategy, t.targetSnapshot!, t.currentRouterState, ); this.currentTransition = overallTransitionState = {...t, targetRouterState}; this.currentNavigation!.targetRouterState = targetRouterState; return overallTransitionState; }), tap(() => { this.events.next(new BeforeActivateRoutes()); }), activateRoutes( this.rootContexts, router.routeReuseStrategy, (evt: Event) => this.events.next(evt), this.inputBindingEnabled, ), // Ensure that if some observable used to drive the transition doesn't // complete, the navigation still finalizes This should never happen, but // this is done as a safety measure to avoid surfacing this error (#49567). take(1), tap({ next: (t: NavigationTransition) => { completed = true; this.lastSuccessfulNavigation = this.currentNavigation; this.events.next( new NavigationEnd( t.id, this.urlSerializer.serialize(t.extractedUrl), this.urlSerializer.serialize(t.urlAfterRedirects!), ), ); this.titleStrategy?.updateTitle(t.targetRouterState!.snapshot); t.resolve(true); }, complete: () => { completed = true; }, }), // There used to be a lot more logic happening directly within the // transition Observable. Some of this logic has been refactored out to // other places but there may still be errors that happen there. This gives // us a way to cancel the transition from the outside. This may also be // required in the future to support something like the abort signal of the // Navigation API where the navigation gets aborted from outside the // transition. takeUntil( this.transitionAbortSubject.pipe( tap((err) => { throw err; }), ), ), 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 = typeof ngDevMode === 'undefined' || ngDevMode ? `Navigation ID ${overallTransitionState.id} is not equal to the current navigation id ${this.navigationId}` : ''; this.cancelNavigationTransition( overallTransitionState, cancelationReason, NavigationCancellationCode.SupersededByNewNavigation, ); } // Only clear current navigation if it is still set to the one that // finalized. if (this.currentTransition?.id === overallTransitionState.id) { this.currentNavigation = null; this.currentTransition = null; } }), catchError((e) => { errored = true; /* This error type is issued during Redirect, and is handled as a * cancellation rather than an error. */ if (isNavigationCancelingError(e)) { this.events.next( new NavigationCancel( overallTransitionState.id, this.urlSerializer.serialize(overallTransitionState.extractedUrl), e.message, e.cancellationCode, ), ); // When redirecting, we need to delay resolving the navigation // promise and push it to the redirect navigation if (!isRedirectingNavigationCancelingError(e)) { overallTransitionState.resolve(false); } else { this.events.next(new RedirectRequest(e.url, e.navigationBehaviorOptions)); } /* All other errors should reset to the router's internal URL reference * to the pre-error state. */ } else { const navigationError = new NavigationError( overallTransitionState.id, this.urlSerializer.serialize(overallTransitionState.extractedUrl), e, overallTransitionState.targetSnapshot ?? undefined, ); try { const navigationErrorHandlerResult = runInInjectionContext( this.environmentInjector, () => this.navigationErrorHandler?.(navigationError), ); if (navigationErrorHandlerResult instanceof RedirectCommand) { const {message, cancellationCode} = redirectingNavigationError( this.urlSerializer, navigationErrorHandlerResult, ); this.events.next( new NavigationCancel( overallTransitionState.id, this.urlSerializer.serialize(overallTransitionState.extractedUrl), message, cancellationCode, ), ); this.events.next( new RedirectRequest( navigationErrorHandlerResult.redirectTo, navigationErrorHandlerResult.navigationBehaviorOptions, ), ); } else { this.events.next(navigationError); throw e; } } catch (ee) { // TODO(atscott): consider flipping the default behavior of // resolveNavigationPromiseOnError to be `resolve(false)` when // undefined. This is the most sane thing to do given that // applications very rarely handle the promise rejection and, as a // result, would get "unhandled promise rejection" console logs. // The vast majority of applications would not be affected by this // change so omitting a migration seems reasonable. Instead, // applications that rely on rejection can specifically opt-in to the // old behavior. if (this.options.resolveNavigationPromiseOnError) { overallTransitionState.resolve(false); } else { overallTransitionState.reject(ee); } } } return EMPTY; }), ); // casting because `pipe` returns observable({}) when called with 8+ arguments }), ) as Observable<NavigationTransition>; } private cancelNavigationTransition( t: NavigationTransition, reason: string, code: NavigationCancellationCode, ) { const navCancel = new NavigationCancel( t.id, this.urlSerializer.serialize(t.extractedUrl), reason, code, ); this.events.next(navCancel); t.resolve(false); } /** * @returns Whether we're navigating to somewhere that is not what the Router is * currently set to. */ private isUpdatingInternalState() { // TODO(atscott): The serializer should likely be used instead of // `UrlTree.toString()`. Custom serializers are often written to handle // things better than the default one (objects, for example will be // [Object object] with the custom serializer and be "the same" when they // aren't). // (Same for isUpdatedBrowserUrl) return ( this.currentTransition?.extractedUrl.toString() !== this.currentTransition?.currentUrlTree.toString() ); } /** * @returns Whether we're updating the browser URL to something new (navigation is going * to somewhere not displayed in the URL bar and we will update the URL * bar if navigation succeeds). */ private isUpdatedBrowserUrl() { // The extracted URL is the part of the URL that this application cares about. `extract` may // return only part of the browser URL and that part may have not changed even if some other // portion of the URL did. const currentBrowserUrl = this.urlHandlingStrategy.extract( this.urlSerializer.parse(this.location.path(true)), ); const targetBrowserUrl = this.currentNavigation?.targetBrowserUrl ?? this.currentNavigation?.extractedUrl; return ( currentBrowserUrl.toString() !== targetBrowserUrl?.toString() && !this.currentNavigation?.extras.skipLocationChange ); } } export function isBrowserTriggeredNavigation(source: NavigationTrigger) { return source !== IMPERATIVE_NAVIGATION; }
{ "end_byte": 36442, "start_byte": 26412, "url": "https://github.com/angular/angular/blob/main/packages/router/src/navigation_transition.ts" }
angular/packages/router/src/shared.ts_0_4620
/** * @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.dev/license */ import {Route, UrlMatchResult} from './models'; import {UrlSegment, UrlSegmentGroup} from './url_tree'; /** * The primary routing outlet. * * @publicApi */ export const PRIMARY_OUTLET = 'primary'; /** * A private symbol used to store the value of `Route.title` inside the `Route.data` if it is a * static string or `Route.resolve` if anything else. This allows us to reuse the existing route * data/resolvers to support the title feature without new instrumentation in the `Router` pipeline. */ export const RouteTitleKey = /* @__PURE__ */ Symbol('RouteTitle'); /** * A collection of matrix and query URL parameters. * @see {@link convertToParamMap} * @see {@link ParamMap} * * @publicApi */ export type Params = { [key: string]: any; }; /** * A map that provides access to the required and optional parameters * specific to a route. * The map supports retrieving a single value with `get()` * or multiple values with `getAll()`. * * @see [URLSearchParams](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams) * * @publicApi */ export interface ParamMap { /** * Reports whether the map contains a given parameter. * @param name The parameter name. * @returns True if the map contains the given parameter, false otherwise. */ has(name: string): boolean; /** * Retrieves a single value for a parameter. * @param name The parameter name. * @return The parameter's single value, * or the first value if the parameter has multiple values, * or `null` when there is no such parameter. */ get(name: string): string | null; /** * Retrieves multiple values for a parameter. * @param name The parameter name. * @return An array containing one or more values, * or an empty array if there is no such parameter. * */ getAll(name: string): string[]; /** Names of the parameters in the map. */ readonly keys: string[]; } class ParamsAsMap implements ParamMap { private params: Params; constructor(params: Params) { this.params = params || {}; } has(name: string): boolean { return Object.prototype.hasOwnProperty.call(this.params, name); } get(name: string): string | null { if (this.has(name)) { const v = this.params[name]; return Array.isArray(v) ? v[0] : v; } return null; } getAll(name: string): string[] { if (this.has(name)) { const v = this.params[name]; return Array.isArray(v) ? v : [v]; } return []; } get keys(): string[] { return Object.keys(this.params); } } /** * Converts a `Params` instance to a `ParamMap`. * @param params The instance to convert. * @returns The new map instance. * * @publicApi */ export function convertToParamMap(params: Params): ParamMap { return new ParamsAsMap(params); } /** * Matches the route configuration (`route`) against the actual URL (`segments`). * * When no matcher is defined on a `Route`, this is the matcher used by the Router by default. * * @param segments The remaining unmatched segments in the current navigation * @param segmentGroup The current segment group being matched * @param route The `Route` to match against. * * @see {@link UrlMatchResult} * @see {@link Route} * * @returns The resulting match information or `null` if the `route` should not match. * @publicApi */ export function defaultUrlMatcher( segments: UrlSegment[], segmentGroup: UrlSegmentGroup, route: Route, ): UrlMatchResult | null { const parts = route.path!.split('/'); if (parts.length > segments.length) { // The actual URL is shorter than the config, no match return null; } if ( route.pathMatch === 'full' && (segmentGroup.hasChildren() || parts.length < segments.length) ) { // The config is longer than the actual URL but we are looking for a full match, return null return null; } const posParams: {[key: string]: UrlSegment} = {}; // Check each config part against the actual URL for (let index = 0; index < parts.length; index++) { const part = parts[index]; const segment = segments[index]; const isParameter = part[0] === ':'; if (isParameter) { posParams[part.substring(1)] = segment; } else if (part !== segment.path) { // The actual URL part does not match the config, no match return null; } } return {consumed: segments.slice(0, parts.length), posParams}; }
{ "end_byte": 4620, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/router/src/shared.ts" }
angular/packages/router/src/events.ts_0_8147
/** * @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.dev/license */ import {NavigationBehaviorOptions, Route} from './models'; import {ActivatedRouteSnapshot, RouterStateSnapshot} from './router_state'; import {UrlTree} from './url_tree'; /** * Identifies the call or event that triggered a navigation. * * * 'imperative': Triggered by `router.navigateByUrl()` or `router.navigate()`. * * 'popstate' : Triggered by a `popstate` event. * * 'hashchange'-: Triggered by a `hashchange` event. * * @publicApi */ export type NavigationTrigger = 'imperative' | 'popstate' | 'hashchange'; export const IMPERATIVE_NAVIGATION = 'imperative'; /** * Identifies the type of a router event. * * @publicApi */ export enum EventType { NavigationStart, NavigationEnd, NavigationCancel, NavigationError, RoutesRecognized, ResolveStart, ResolveEnd, GuardsCheckStart, GuardsCheckEnd, RouteConfigLoadStart, RouteConfigLoadEnd, ChildActivationStart, ChildActivationEnd, ActivationStart, ActivationEnd, Scroll, NavigationSkipped, } /** * Base for events the router goes through, as opposed to events tied to a specific * route. Fired one time for any given navigation. * * The following code shows how a class subscribes to router events. * * ```ts * import {Event, RouterEvent, Router} from '@angular/router'; * * class MyService { * constructor(public router: Router) { * router.events.pipe( * filter((e: Event | RouterEvent): e is RouterEvent => e instanceof RouterEvent) * ).subscribe((e: RouterEvent) => { * // Do something * }); * } * } * ``` * * @see {@link Event} * @see [Router events summary](guide/routing/router-reference#router-events) * @publicApi */ export class RouterEvent { constructor( /** A unique ID that the router assigns to every router navigation. */ public id: number, /** The URL that is the destination for this navigation. */ public url: string, ) {} } /** * An event triggered when a navigation starts. * * @publicApi */ export class NavigationStart extends RouterEvent { readonly type = EventType.NavigationStart; /** * Identifies the call or event that triggered the navigation. * An `imperative` trigger is a call to `router.navigateByUrl()` or `router.navigate()`. * * @see {@link NavigationEnd} * @see {@link NavigationCancel} * @see {@link NavigationError} */ navigationTrigger?: NavigationTrigger; /** * The navigation state that was previously supplied to the `pushState` call, * when the navigation is triggered by a `popstate` event. Otherwise null. * * The state object is defined by `NavigationExtras`, and contains any * developer-defined state value, as well as a unique ID that * the router assigns to every router transition/navigation. * * From the perspective of the router, the router never "goes back". * When the user clicks on the back button in the browser, * a new navigation ID is created. * * Use the ID in this previous-state object to differentiate between a newly created * state and one returned to by a `popstate` event, so that you can restore some * remembered state, such as scroll position. * */ restoredState?: {[k: string]: any; navigationId: number} | null; constructor( /** @docsNotRequired */ id: number, /** @docsNotRequired */ url: string, /** @docsNotRequired */ navigationTrigger: NavigationTrigger = 'imperative', /** @docsNotRequired */ restoredState: {[k: string]: any; navigationId: number} | null = null, ) { super(id, url); this.navigationTrigger = navigationTrigger; this.restoredState = restoredState; } /** @docsNotRequired */ override toString(): string { return `NavigationStart(id: ${this.id}, url: '${this.url}')`; } } /** * An event triggered when a navigation ends successfully. * * @see {@link NavigationStart} * @see {@link NavigationCancel} * @see {@link NavigationError} * * @publicApi */ export class NavigationEnd extends RouterEvent { readonly type = EventType.NavigationEnd; constructor( /** @docsNotRequired */ id: number, /** @docsNotRequired */ url: string, /** @docsNotRequired */ public urlAfterRedirects: string, ) { super(id, url); } /** @docsNotRequired */ override toString(): string { return `NavigationEnd(id: ${this.id}, url: '${this.url}', urlAfterRedirects: '${this.urlAfterRedirects}')`; } } /** * A code for the `NavigationCancel` event of the `Router` to indicate the * reason a navigation failed. * * @publicApi */ export enum NavigationCancellationCode { /** * A navigation failed because a guard returned a `UrlTree` to redirect. */ Redirect, /** * A navigation failed because a more recent navigation started. */ SupersededByNewNavigation, /** * A navigation failed because one of the resolvers completed without emitting a value. */ NoDataFromResolver, /** * A navigation failed because a guard returned `false`. */ GuardRejected, } /** * A code for the `NavigationSkipped` event of the `Router` to indicate the * reason a navigation was skipped. * * @publicApi */ export enum NavigationSkippedCode { /** * A navigation was skipped because the navigation URL was the same as the current Router URL. */ IgnoredSameUrlNavigation, /** * A navigation was skipped because the configured `UrlHandlingStrategy` return `false` for both * the current Router URL and the target of the navigation. * * @see {@link UrlHandlingStrategy} */ IgnoredByUrlHandlingStrategy, } /** * An event triggered when a navigation is canceled, directly or indirectly. * This can happen for several reasons including when a route guard * returns `false` or initiates a redirect by returning a `UrlTree`. * * @see {@link NavigationStart} * @see {@link NavigationEnd} * @see {@link NavigationError} * * @publicApi */ export class NavigationCancel extends RouterEvent { readonly type = EventType.NavigationCancel; constructor( /** @docsNotRequired */ id: number, /** @docsNotRequired */ url: string, /** * A description of why the navigation was cancelled. For debug purposes only. Use `code` * instead for a stable cancellation reason that can be used in production. */ public reason: string, /** * A code to indicate why the navigation was canceled. This cancellation code is stable for * the reason and can be relied on whereas the `reason` string could change and should not be * used in production. */ readonly code?: NavigationCancellationCode, ) { super(id, url); } /** @docsNotRequired */ override toString(): string { return `NavigationCancel(id: ${this.id}, url: '${this.url}')`; } } /** * An event triggered when a navigation is skipped. * This can happen for a couple reasons including onSameUrlHandling * is set to `ignore` and the navigation URL is not different than the * current state. * * @publicApi */ export class NavigationSkipped extends RouterEvent { readonly type = EventType.NavigationSkipped; constructor( /** @docsNotRequired */ id: number, /** @docsNotRequired */ url: string, /** * A description of why the navigation was skipped. For debug purposes only. Use `code` * instead for a stable skipped reason that can be used in production. */ public reason: string, /** * A code to indicate why the navigation was skipped. This code is stable for * the reason and can be relied on whereas the `reason` string could change and should not be * used in production. */ readonly code?: NavigationSkippedCode, ) { super(id, url); } } /** * An event triggered when a navigation fails due to an unexpected error. * * @see {@link NavigationStart} * @see {@link NavigationEnd} * @see {@link NavigationCancel} * * @publicApi */
{ "end_byte": 8147, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/router/src/events.ts" }
angular/packages/router/src/events.ts_8148_16056
export class NavigationError extends RouterEvent { readonly type = EventType.NavigationError; constructor( /** @docsNotRequired */ id: number, /** @docsNotRequired */ url: string, /** @docsNotRequired */ public error: any, /** * The target of the navigation when the error occurred. * * Note that this can be `undefined` because an error could have occurred before the * `RouterStateSnapshot` was created for the navigation. */ readonly target?: RouterStateSnapshot, ) { super(id, url); } /** @docsNotRequired */ override toString(): string { return `NavigationError(id: ${this.id}, url: '${this.url}', error: ${this.error})`; } } /** * An event triggered when routes are recognized. * * @publicApi */ export class RoutesRecognized extends RouterEvent { readonly type = EventType.RoutesRecognized; constructor( /** @docsNotRequired */ id: number, /** @docsNotRequired */ url: string, /** @docsNotRequired */ public urlAfterRedirects: string, /** @docsNotRequired */ public state: RouterStateSnapshot, ) { super(id, url); } /** @docsNotRequired */ override toString(): string { return `RoutesRecognized(id: ${this.id}, url: '${this.url}', urlAfterRedirects: '${this.urlAfterRedirects}', state: ${this.state})`; } } /** * An event triggered at the start of the Guard phase of routing. * * @see {@link GuardsCheckEnd} * * @publicApi */ export class GuardsCheckStart extends RouterEvent { readonly type = EventType.GuardsCheckStart; constructor( /** @docsNotRequired */ id: number, /** @docsNotRequired */ url: string, /** @docsNotRequired */ public urlAfterRedirects: string, /** @docsNotRequired */ public state: RouterStateSnapshot, ) { super(id, url); } override toString(): string { return `GuardsCheckStart(id: ${this.id}, url: '${this.url}', urlAfterRedirects: '${this.urlAfterRedirects}', state: ${this.state})`; } } /** * An event triggered at the end of the Guard phase of routing. * * @see {@link GuardsCheckStart} * * @publicApi */ export class GuardsCheckEnd extends RouterEvent { readonly type = EventType.GuardsCheckEnd; constructor( /** @docsNotRequired */ id: number, /** @docsNotRequired */ url: string, /** @docsNotRequired */ public urlAfterRedirects: string, /** @docsNotRequired */ public state: RouterStateSnapshot, /** @docsNotRequired */ public shouldActivate: boolean, ) { super(id, url); } override toString(): string { return `GuardsCheckEnd(id: ${this.id}, url: '${this.url}', urlAfterRedirects: '${this.urlAfterRedirects}', state: ${this.state}, shouldActivate: ${this.shouldActivate})`; } } /** * An event triggered at the start of the Resolve phase of routing. * * Runs in the "resolve" phase whether or not there is anything to resolve. * In future, may change to only run when there are things to be resolved. * * @see {@link ResolveEnd} * * @publicApi */ export class ResolveStart extends RouterEvent { readonly type = EventType.ResolveStart; constructor( /** @docsNotRequired */ id: number, /** @docsNotRequired */ url: string, /** @docsNotRequired */ public urlAfterRedirects: string, /** @docsNotRequired */ public state: RouterStateSnapshot, ) { super(id, url); } override toString(): string { return `ResolveStart(id: ${this.id}, url: '${this.url}', urlAfterRedirects: '${this.urlAfterRedirects}', state: ${this.state})`; } } /** * An event triggered at the end of the Resolve phase of routing. * @see {@link ResolveStart} * * @publicApi */ export class ResolveEnd extends RouterEvent { readonly type = EventType.ResolveEnd; constructor( /** @docsNotRequired */ id: number, /** @docsNotRequired */ url: string, /** @docsNotRequired */ public urlAfterRedirects: string, /** @docsNotRequired */ public state: RouterStateSnapshot, ) { super(id, url); } override toString(): string { return `ResolveEnd(id: ${this.id}, url: '${this.url}', urlAfterRedirects: '${this.urlAfterRedirects}', state: ${this.state})`; } } /** * An event triggered before lazy loading a route configuration. * * @see {@link RouteConfigLoadEnd} * * @publicApi */ export class RouteConfigLoadStart { readonly type = EventType.RouteConfigLoadStart; constructor( /** @docsNotRequired */ public route: Route, ) {} toString(): string { return `RouteConfigLoadStart(path: ${this.route.path})`; } } /** * An event triggered when a route has been lazy loaded. * * @see {@link RouteConfigLoadStart} * * @publicApi */ export class RouteConfigLoadEnd { readonly type = EventType.RouteConfigLoadEnd; constructor( /** @docsNotRequired */ public route: Route, ) {} toString(): string { return `RouteConfigLoadEnd(path: ${this.route.path})`; } } /** * An event triggered at the start of the child-activation * part of the Resolve phase of routing. * @see {@link ChildActivationEnd} * @see {@link ResolveStart} * * @publicApi */ export class ChildActivationStart { readonly type = EventType.ChildActivationStart; constructor( /** @docsNotRequired */ public snapshot: ActivatedRouteSnapshot, ) {} toString(): string { const path = (this.snapshot.routeConfig && this.snapshot.routeConfig.path) || ''; return `ChildActivationStart(path: '${path}')`; } } /** * An event triggered at the end of the child-activation part * of the Resolve phase of routing. * @see {@link ChildActivationStart} * @see {@link ResolveStart} * @publicApi */ export class ChildActivationEnd { readonly type = EventType.ChildActivationEnd; constructor( /** @docsNotRequired */ public snapshot: ActivatedRouteSnapshot, ) {} toString(): string { const path = (this.snapshot.routeConfig && this.snapshot.routeConfig.path) || ''; return `ChildActivationEnd(path: '${path}')`; } } /** * An event triggered at the start of the activation part * of the Resolve phase of routing. * @see {@link ActivationEnd} * @see {@link ResolveStart} * * @publicApi */ export class ActivationStart { readonly type = EventType.ActivationStart; constructor( /** @docsNotRequired */ public snapshot: ActivatedRouteSnapshot, ) {} toString(): string { const path = (this.snapshot.routeConfig && this.snapshot.routeConfig.path) || ''; return `ActivationStart(path: '${path}')`; } } /** * An event triggered at the end of the activation part * of the Resolve phase of routing. * @see {@link ActivationStart} * @see {@link ResolveStart} * * @publicApi */ export class ActivationEnd { readonly type = EventType.ActivationEnd; constructor( /** @docsNotRequired */ public snapshot: ActivatedRouteSnapshot, ) {} toString(): string { const path = (this.snapshot.routeConfig && this.snapshot.routeConfig.path) || ''; return `ActivationEnd(path: '${path}')`; } } /** * An event triggered by scrolling. * * @publicApi */ export class Scroll { readonly type = EventType.Scroll; constructor( /** @docsNotRequired */ readonly routerEvent: NavigationEnd | NavigationSkipped, /** @docsNotRequired */ readonly position: [number, number] | null, /** @docsNotRequired */ readonly anchor: string | null, ) {} toString(): string { const pos = this.position ? `${this.position[0]}, ${this.position[1]}` : null; return `Scroll(anchor: '${this.anchor}', position: '${pos}')`; } } export class BeforeActivateRoutes {} export class RedirectRequest { constructor( readonly url: UrlTree, readonly navigationBehaviorOptions: NavigationBehaviorOptions | undefined, ) {} } export type PrivateRouterEvents = BeforeActivateRoutes | RedirectRequest;
{ "end_byte": 16056, "start_byte": 8148, "url": "https://github.com/angular/angular/blob/main/packages/router/src/events.ts" }
angular/packages/router/src/events.ts_16058_20992
/** * Router events that allow you to track the lifecycle of the router. * * The events occur in the following sequence: * * * [NavigationStart](api/router/NavigationStart): Navigation starts. * * [RouteConfigLoadStart](api/router/RouteConfigLoadStart): Before * the router [lazy loads](guide/routing/common-router-tasks#lazy-loading) a route configuration. * * [RouteConfigLoadEnd](api/router/RouteConfigLoadEnd): After a route has been lazy loaded. * * [RoutesRecognized](api/router/RoutesRecognized): When the router parses the URL * and the routes are recognized. * * [GuardsCheckStart](api/router/GuardsCheckStart): When the router begins the *guards* * phase of routing. * * [ChildActivationStart](api/router/ChildActivationStart): When the router * begins activating a route's children. * * [ActivationStart](api/router/ActivationStart): When the router begins activating a route. * * [GuardsCheckEnd](api/router/GuardsCheckEnd): When the router finishes the *guards* * phase of routing successfully. * * [ResolveStart](api/router/ResolveStart): When the router begins the *resolve* * phase of routing. * * [ResolveEnd](api/router/ResolveEnd): When the router finishes the *resolve* * phase of routing successfully. * * [ChildActivationEnd](api/router/ChildActivationEnd): When the router finishes * activating a route's children. * * [ActivationEnd](api/router/ActivationEnd): When the router finishes activating a route. * * [NavigationEnd](api/router/NavigationEnd): When navigation ends successfully. * * [NavigationCancel](api/router/NavigationCancel): When navigation is canceled. * * [NavigationError](api/router/NavigationError): When navigation fails * due to an unexpected error. * * [Scroll](api/router/Scroll): When the user scrolls. * * @publicApi */ export type Event = | NavigationStart | NavigationEnd | NavigationCancel | NavigationError | RoutesRecognized | GuardsCheckStart | GuardsCheckEnd | RouteConfigLoadStart | RouteConfigLoadEnd | ChildActivationStart | ChildActivationEnd | ActivationStart | ActivationEnd | Scroll | ResolveStart | ResolveEnd | NavigationSkipped; export function stringifyEvent(routerEvent: Event): string { switch (routerEvent.type) { case EventType.ActivationEnd: return `ActivationEnd(path: '${routerEvent.snapshot.routeConfig?.path || ''}')`; case EventType.ActivationStart: return `ActivationStart(path: '${routerEvent.snapshot.routeConfig?.path || ''}')`; case EventType.ChildActivationEnd: return `ChildActivationEnd(path: '${routerEvent.snapshot.routeConfig?.path || ''}')`; case EventType.ChildActivationStart: return `ChildActivationStart(path: '${routerEvent.snapshot.routeConfig?.path || ''}')`; case EventType.GuardsCheckEnd: return `GuardsCheckEnd(id: ${routerEvent.id}, url: '${routerEvent.url}', urlAfterRedirects: '${routerEvent.urlAfterRedirects}', state: ${routerEvent.state}, shouldActivate: ${routerEvent.shouldActivate})`; case EventType.GuardsCheckStart: return `GuardsCheckStart(id: ${routerEvent.id}, url: '${routerEvent.url}', urlAfterRedirects: '${routerEvent.urlAfterRedirects}', state: ${routerEvent.state})`; case EventType.NavigationCancel: return `NavigationCancel(id: ${routerEvent.id}, url: '${routerEvent.url}')`; case EventType.NavigationSkipped: return `NavigationSkipped(id: ${routerEvent.id}, url: '${routerEvent.url}')`; case EventType.NavigationEnd: return `NavigationEnd(id: ${routerEvent.id}, url: '${routerEvent.url}', urlAfterRedirects: '${routerEvent.urlAfterRedirects}')`; case EventType.NavigationError: return `NavigationError(id: ${routerEvent.id}, url: '${routerEvent.url}', error: ${routerEvent.error})`; case EventType.NavigationStart: return `NavigationStart(id: ${routerEvent.id}, url: '${routerEvent.url}')`; case EventType.ResolveEnd: return `ResolveEnd(id: ${routerEvent.id}, url: '${routerEvent.url}', urlAfterRedirects: '${routerEvent.urlAfterRedirects}', state: ${routerEvent.state})`; case EventType.ResolveStart: return `ResolveStart(id: ${routerEvent.id}, url: '${routerEvent.url}', urlAfterRedirects: '${routerEvent.urlAfterRedirects}', state: ${routerEvent.state})`; case EventType.RouteConfigLoadEnd: return `RouteConfigLoadEnd(path: ${routerEvent.route.path})`; case EventType.RouteConfigLoadStart: return `RouteConfigLoadStart(path: ${routerEvent.route.path})`; case EventType.RoutesRecognized: return `RoutesRecognized(id: ${routerEvent.id}, url: '${routerEvent.url}', urlAfterRedirects: '${routerEvent.urlAfterRedirects}', state: ${routerEvent.state})`; case EventType.Scroll: const pos = routerEvent.position ? `${routerEvent.position[0]}, ${routerEvent.position[1]}` : null; return `Scroll(anchor: '${routerEvent.anchor}', position: '${pos}')`; } }
{ "end_byte": 20992, "start_byte": 16058, "url": "https://github.com/angular/angular/blob/main/packages/router/src/events.ts" }
angular/packages/router/src/create_router_state.ts_0_2826
/** * @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.dev/license */ import {BehaviorSubject} from 'rxjs'; import {DetachedRouteHandleInternal, RouteReuseStrategy} from './route_reuse_strategy'; import { ActivatedRoute, ActivatedRouteSnapshot, RouterState, RouterStateSnapshot, } from './router_state'; import {TreeNode} from './utils/tree'; export function createRouterState( routeReuseStrategy: RouteReuseStrategy, curr: RouterStateSnapshot, prevState: RouterState, ): RouterState { const root = createNode(routeReuseStrategy, curr._root, prevState ? prevState._root : undefined); return new RouterState(root, curr); } function createNode( routeReuseStrategy: RouteReuseStrategy, curr: TreeNode<ActivatedRouteSnapshot>, prevState?: TreeNode<ActivatedRoute>, ): TreeNode<ActivatedRoute> { // reuse an activated route that is currently displayed on the screen if (prevState && routeReuseStrategy.shouldReuseRoute(curr.value, prevState.value.snapshot)) { const value = prevState.value; value._futureSnapshot = curr.value; const children = createOrReuseChildren(routeReuseStrategy, curr, prevState); return new TreeNode<ActivatedRoute>(value, children); } else { if (routeReuseStrategy.shouldAttach(curr.value)) { // retrieve an activated route that is used to be displayed, but is not currently displayed const detachedRouteHandle = routeReuseStrategy.retrieve(curr.value); if (detachedRouteHandle !== null) { const tree = (detachedRouteHandle as DetachedRouteHandleInternal).route; tree.value._futureSnapshot = curr.value; tree.children = curr.children.map((c) => createNode(routeReuseStrategy, c)); return tree; } } const value = createActivatedRoute(curr.value); const children = curr.children.map((c) => createNode(routeReuseStrategy, c)); return new TreeNode<ActivatedRoute>(value, children); } } function createOrReuseChildren( routeReuseStrategy: RouteReuseStrategy, curr: TreeNode<ActivatedRouteSnapshot>, prevState: TreeNode<ActivatedRoute>, ) { return curr.children.map((child) => { for (const p of prevState.children) { if (routeReuseStrategy.shouldReuseRoute(child.value, p.value.snapshot)) { return createNode(routeReuseStrategy, child, p); } } return createNode(routeReuseStrategy, child); }); } function createActivatedRoute(c: ActivatedRouteSnapshot) { return new ActivatedRoute( new BehaviorSubject(c.url), new BehaviorSubject(c.params), new BehaviorSubject(c.queryParams), new BehaviorSubject(c.fragment), new BehaviorSubject(c.data), c.outlet, c.component, c, ); }
{ "end_byte": 2826, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/router/src/create_router_state.ts" }
angular/packages/router/src/index.ts_0_3729
/** * @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.dev/license */ export {createUrlTreeFromSnapshot} from './create_url_tree'; export {RouterLink, RouterLinkWithHref} from './directives/router_link'; export {RouterLinkActive} from './directives/router_link_active'; export {RouterOutlet, ROUTER_OUTLET_DATA, RouterOutletContract} from './directives/router_outlet'; export { ActivationEnd, ActivationStart, ChildActivationEnd, ChildActivationStart, Event, EventType, GuardsCheckEnd, GuardsCheckStart, NavigationCancel, NavigationCancellationCode as NavigationCancellationCode, NavigationEnd, NavigationError, NavigationSkipped, NavigationSkippedCode, NavigationStart, ResolveEnd, ResolveStart, RouteConfigLoadEnd, RouteConfigLoadStart, RouterEvent, RoutesRecognized, Scroll, } from './events'; export { CanActivateChildFn, MaybeAsync, GuardResult, CanActivateFn, CanDeactivateFn, CanLoadFn, CanMatchFn, Data, DefaultExport, LoadChildren, LoadChildrenCallback, NavigationBehaviorOptions, OnSameUrlNavigation, QueryParamsHandling, RedirectFunction, ResolveData, ResolveFn, Route, Routes, RunGuardsAndResolvers, UrlMatcher, UrlMatchResult, RedirectCommand, CanActivate, CanActivateChild, CanDeactivate, CanLoad, CanMatch, Resolve, } from './models'; export {ViewTransitionInfo, ViewTransitionsFeatureOptions} from './utils/view_transition'; export * from './models_deprecated'; export {Navigation, NavigationExtras, UrlCreationOptions} from './navigation_transition'; export {DefaultTitleStrategy, TitleStrategy} from './page_title_strategy'; export { ComponentInputBindingFeature, DebugTracingFeature, DisabledInitialNavigationFeature, withViewTransitions, ViewTransitionsFeature, EnabledBlockingInitialNavigationFeature, InitialNavigationFeature, InMemoryScrollingFeature, NavigationErrorHandlerFeature, PreloadingFeature, provideRouter, provideRoutes, RouterConfigurationFeature, RouterFeature, RouterFeatures, RouterHashLocationFeature, withComponentInputBinding, withDebugTracing, withDisabledInitialNavigation, withEnabledBlockingInitialNavigation, withHashLocation, withInMemoryScrolling, withNavigationErrorHandler, withPreloading, withRouterConfig, } from './provide_router'; export { BaseRouteReuseStrategy, DetachedRouteHandle, RouteReuseStrategy, } from './route_reuse_strategy'; export {Router} from './router'; export { ExtraOptions, InitialNavigation, InMemoryScrollingOptions, ROUTER_CONFIGURATION, RouterConfigOptions, } from './router_config'; export {ROUTES} from './router_config_loader'; export {ROUTER_INITIALIZER, RouterModule} from './router_module'; export {ChildrenOutletContexts, OutletContext} from './router_outlet_context'; export { NoPreloading, PreloadAllModules, PreloadingStrategy, RouterPreloader, } from './router_preloader'; export { ActivatedRoute, ActivatedRouteSnapshot, RouterState, RouterStateSnapshot, } from './router_state'; export {convertToParamMap, defaultUrlMatcher, ParamMap, Params, PRIMARY_OUTLET} from './shared'; export {UrlHandlingStrategy} from './url_handling_strategy'; export { DefaultUrlSerializer, IsActiveMatchOptions, UrlSegment, UrlSegmentGroup, UrlSerializer, UrlTree, } from './url_tree'; export { mapToCanActivate, mapToCanActivateChild, mapToCanDeactivate, mapToCanMatch, mapToResolve, } from './utils/functional_guards'; export {VERSION} from './version'; export * from './private_export'; import './router_devtools';
{ "end_byte": 3729, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/router/src/index.ts" }
angular/packages/router/src/models.ts_0_8176
/** * @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.dev/license */ import { EnvironmentInjector, EnvironmentProviders, NgModuleFactory, Provider, ProviderToken, Type, } from '@angular/core'; import {Observable} from 'rxjs'; import {ActivatedRouteSnapshot, RouterStateSnapshot} from './router_state'; import {UrlSegment, UrlSegmentGroup, UrlTree} from './url_tree'; /** * How to handle a navigation request to the current URL. One of: * * - `'ignore'` : The router ignores the request it is the same as the current state. * - `'reload'` : The router processes the URL even if it is not different from the current state. * One example of when you might want this option is if a `canMatch` guard depends on * application state and initially rejects navigation to a route. After fixing the state, you want * to re-navigate to the same URL so the route with the `canMatch` guard can activate. * * 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`. Additionally, * resolvers and most guards for routes do not run unless the path or path params changed * (configured by `runGuardsAndResolvers`). * * @publicApi * @see {@link RouteReuseStrategy} * @see {@link RunGuardsAndResolvers} * @see {@link NavigationBehaviorOptions} * @see {@link RouterConfigOptions} */ export type OnSameUrlNavigation = 'reload' | 'ignore'; /** * The `InjectionToken` and `@Injectable` classes for guards and resolvers are deprecated in favor * of plain JavaScript functions instead.. Dependency injection can still be achieved using the * [`inject`](api/core/inject) function from `@angular/core` and an injectable class can be used as * a functional guard using [`inject`](api/core/inject): `canActivate: [() => * inject(myGuard).canActivate()]`. * * @deprecated * @see {@link CanMatchFn} * @see {@link CanLoadFn} * @see {@link CanActivateFn} * @see {@link CanActivateChildFn} * @see {@link CanDeactivateFn} * @see {@link ResolveFn} * @see {@link core/inject} * @publicApi */ export type DeprecatedGuard = ProviderToken<any> | any; /** * The supported types that can be returned from a `Router` guard. * * @see [Routing guide](guide/routing/common-router-tasks#preventing-unauthorized-access) * @publicApi */ export type GuardResult = boolean | UrlTree | RedirectCommand; /** * Can be returned by a `Router` guard to instruct the `Router` to redirect rather than continue * processing the path of the in-flight navigation. The `redirectTo` indicates _where_ the new * navigation should go to and the optional `navigationBehaviorOptions` can provide more information * about _how_ to perform the navigation. * * ```ts * const route: Route = { * path: "user/:userId", * component: User, * canActivate: [ * () => { * const router = inject(Router); * const authService = inject(AuthenticationService); * * if (!authService.isLoggedIn()) { * const loginPath = router.parseUrl("/login"); * return new RedirectCommand(loginPath, { * skipLocationChange: "true", * }); * } * * return true; * }, * ], * }; * ``` * @see [Routing guide](guide/routing/common-router-tasks#preventing-unauthorized-access) * * @publicApi */ export class RedirectCommand { constructor( readonly redirectTo: UrlTree, readonly navigationBehaviorOptions?: NavigationBehaviorOptions, ) {} } /** * Type used to represent a value which may be synchronous or async. * * @publicApi */ export type MaybeAsync<T> = T | Observable<T> | Promise<T>; /** * Represents a route configuration for the Router service. * An array of `Route` objects, used in `Router.config` and for nested route configurations * in `Route.children`. * * @see {@link Route} * @see {@link Router} * @see [Router configuration guide](guide/routing/router-reference#configuration) * @publicApi */ export type Routes = Route[]; /** * Represents the result of matching URLs with a custom matching function. * * * `consumed` is an array of the consumed URL segments. * * `posParams` is a map of positional parameters. * * @see {@link UrlMatcher} * @publicApi */ export type UrlMatchResult = { consumed: UrlSegment[]; posParams?: {[name: string]: UrlSegment}; }; /** * A function for matching a route against URLs. Implement a custom URL matcher * for `Route.matcher` when a combination of `path` and `pathMatch` * is not expressive enough. Cannot be used together with `path` and `pathMatch`. * * The function takes the following arguments and returns a `UrlMatchResult` object. * * *segments* : An array of URL segments. * * *group* : A segment group. * * *route* : The route to match against. * * The following example implementation matches HTML files. * * ``` * export function htmlFiles(url: UrlSegment[]) { * return url.length === 1 && url[0].path.endsWith('.html') ? ({consumed: url}) : null; * } * * export const routes = [{ matcher: htmlFiles, component: AnyComponent }]; * ``` * * @publicApi */ export type UrlMatcher = ( segments: UrlSegment[], group: UrlSegmentGroup, route: Route, ) => UrlMatchResult | null; /** * * Represents static data associated with a particular route. * * @see {@link Route#data} * * @publicApi */ export type Data = { [key: string | symbol]: any; }; /** * * Represents the resolved data associated with a particular route. * * Returning a `RedirectCommand` directs the router to cancel the current navigation and redirect to * the location provided in the `RedirectCommand`. Note that there are no ordering guarantees when * resolvers execute. If multiple resolvers would return a `RedirectCommand`, only the first one * returned will be used. * * @see {@link Route#resolve} * * @publicApi */ export type ResolveData = { [key: string | symbol]: ResolveFn<unknown> | DeprecatedGuard; }; /** * An ES Module object with a default export of the given type. * * @see {@link Route#loadComponent} * @see {@link LoadChildrenCallback} * * @publicApi */ export interface DefaultExport<T> { /** * Default exports are bound under the name `"default"`, per the ES Module spec: * https://tc39.es/ecma262/#table-export-forms-mapping-to-exportentry-records */ default: T; } /** * * A function that is called to resolve a collection of lazy-loaded routes. * Must be an arrow function of the following form: * `() => import('...').then(mod => mod.MODULE)` * or * `() => import('...').then(mod => mod.ROUTES)` * * For example: * * ``` * [{ * path: 'lazy', * loadChildren: () => import('./lazy-route/lazy.module').then(mod => mod.LazyModule), * }]; * ``` * or * ``` * [{ * path: 'lazy', * loadChildren: () => import('./lazy-route/lazy.routes').then(mod => mod.ROUTES), * }]; * ``` * * If the lazy-loaded routes are exported via a `default` export, the `.then` can be omitted: * ``` * [{ * path: 'lazy', * loadChildren: () => import('./lazy-route/lazy.routes'), * }]; * ``` * * @see {@link Route#loadChildren} * @publicApi */ export type LoadChildrenCallback = () => | Type<any> | NgModuleFactory<any> | Routes | Observable<Type<any> | Routes | DefaultExport<Type<any>> | DefaultExport<Routes>> | Promise< NgModuleFactory<any> | Type<any> | Routes | DefaultExport<Type<any>> | DefaultExport<Routes> >; /** * * A function that returns a set of routes to load. * * @see {@link LoadChildrenCallback} * @publicApi */ export type LoadChildren = LoadChildrenCallback;
{ "end_byte": 8176, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/router/src/models.ts" }
angular/packages/router/src/models.ts_8178_10751
/** * * How to handle query parameters in a router link. * One of: * - `"merge"` : Merge new parameters with current parameters. * - `"preserve"` : Preserve current parameters. * - `"replace"` : Replace current parameters with new parameters. This is the default behavior. * - `""` : For legacy reasons, the same as `'replace'`. * * @see {@link UrlCreationOptions#queryParamsHandling} * @see {@link RouterLink} * @publicApi */ export type QueryParamsHandling = 'merge' | 'preserve' | 'replace' | ''; /** * The type for the function that can be used to handle redirects when the path matches a `Route` config. * * The `RedirectFunction` does have access to the full * `ActivatedRouteSnapshot` interface. Some data are not accurately known * at the route matching phase. For example, resolvers are not run until * later, so any resolved title would not be populated. The same goes for lazy * loaded components. This is also true for all the snapshots up to the * root, so properties that include parents (root, parent, pathFromRoot) * are also excluded. And naturally, the full route matching hasn't yet * happened so firstChild and children are not available either. * * @see {@link Route#redirectTo} * @publicApi */ export type RedirectFunction = ( redirectData: Pick< ActivatedRouteSnapshot, 'routeConfig' | 'url' | 'params' | 'queryParams' | 'fragment' | 'data' | 'outlet' | 'title' >, ) => string | UrlTree; /** * A policy for when to run guards and resolvers on a route. * * Guards and/or resolvers will always run when a route is activated or deactivated. When a route is * unchanged, the default behavior is the same as `paramsChange`. * * `paramsChange` : Rerun the guards and resolvers when path or * path param changes. This does not include query parameters. This option is the default. * - `always` : Run on every execution. * - `pathParamsChange` : Rerun guards and resolvers when the path params * change. This does not compare matrix or query parameters. * - `paramsOrQueryParamsChange` : Run when path, matrix, or query parameters change. * - `pathParamsOrQueryParamsChange` : Rerun guards and resolvers when the path params * change or query params have changed. This does not include matrix parameters. * * @see {@link Route#runGuardsAndResolvers} * @publicApi */ export type RunGuardsAndResolvers = | 'pathParamsChange' | 'pathParamsOrQueryParamsChange' | 'paramsChange' | 'paramsOrQueryParamsChange' | 'always' | ((from: ActivatedRouteSnapshot, to: ActivatedRouteSnapshot) => boolean);
{ "end_byte": 10751, "start_byte": 8178, "url": "https://github.com/angular/angular/blob/main/packages/router/src/models.ts" }
angular/packages/router/src/models.ts_10753_17056
/** * A configuration object that defines a single route. * A set of routes are collected in a `Routes` array to define a `Router` configuration. * The router attempts to match segments of a given URL against each route, * using the configuration options defined in this object. * * Supports static, parameterized, redirect, and wildcard routes, as well as * custom route data and resolve methods. * * For detailed usage information, see the [Routing Guide](guide/routing/common-router-tasks). * * @usageNotes * * ### Simple Configuration * * The following route specifies that when navigating to, for example, * `/team/11/user/bob`, the router creates the 'Team' component * with the 'User' child component in it. * * ``` * [{ * path: 'team/:id', * component: Team, * children: [{ * path: 'user/:name', * component: User * }] * }] * ``` * * ### Multiple Outlets * * The following route creates sibling components with multiple outlets. * When navigating to `/team/11(aux:chat/jim)`, the router creates the 'Team' component next to * the 'Chat' component. The 'Chat' component is placed into the 'aux' outlet. * * ``` * [{ * path: 'team/:id', * component: Team * }, { * path: 'chat/:user', * component: Chat * outlet: 'aux' * }] * ``` * * ### Wild Cards * * The following route uses wild-card notation to specify a component * that is always instantiated regardless of where you navigate to. * * ``` * [{ * path: '**', * component: WildcardComponent * }] * ``` * * ### Redirects * * The following route uses the `redirectTo` property to ignore a segment of * a given URL when looking for a child path. * * When navigating to '/team/11/legacy/user/jim', the router changes the URL segment * '/team/11/legacy/user/jim' to '/team/11/user/jim', and then instantiates * the Team component with the User child component in it. * * ``` * [{ * path: 'team/:id', * component: Team, * children: [{ * path: 'legacy/user/:name', * redirectTo: 'user/:name' * }, { * path: 'user/:name', * component: User * }] * }] * ``` * * The redirect path can be relative, as shown in this example, or absolute. * If we change the `redirectTo` value in the example to the absolute URL segment '/user/:name', * the result URL is also absolute, '/user/jim'. * ### Empty Path * * Empty-path route configurations can be used to instantiate components that do not 'consume' * any URL segments. * * In the following configuration, when navigating to * `/team/11`, the router instantiates the 'AllUsers' component. * * ``` * [{ * path: 'team/:id', * component: Team, * children: [{ * path: '', * component: AllUsers * }, { * path: 'user/:name', * component: User * }] * }] * ``` * * Empty-path routes can have children. In the following example, when navigating * to `/team/11/user/jim`, the router instantiates the wrapper component with * the user component in it. * * Note that an empty path route inherits its parent's parameters and data. * * ``` * [{ * path: 'team/:id', * component: Team, * children: [{ * path: '', * component: WrapperCmp, * children: [{ * path: 'user/:name', * component: User * }] * }] * }] * ``` * * ### Matching Strategy * * The default path-match strategy is 'prefix', which means that the router * checks URL elements from the left to see if the URL matches a specified path. * For example, '/team/11/user' matches 'team/:id'. * * ``` * [{ * path: '', * pathMatch: 'prefix', //default * redirectTo: 'main' * }, { * path: 'main', * component: Main * }] * ``` * * You can specify the path-match strategy 'full' to make sure that the path * covers the whole unconsumed URL. It is important to do this when redirecting * empty-path routes. Otherwise, because an empty path is a prefix of any URL, * the router would apply the redirect even when navigating to the redirect destination, * creating an endless loop. * * In the following example, supplying the 'full' `pathMatch` strategy ensures * that the router applies the redirect if and only if navigating to '/'. * * ``` * [{ * path: '', * pathMatch: 'full', * redirectTo: 'main' * }, { * path: 'main', * component: Main * }] * ``` * * ### Componentless Routes * * You can share parameters between sibling components. * For example, suppose that two sibling components should go next to each other, * and both of them require an ID parameter. You can accomplish this using a route * that does not specify a component at the top level. * * In the following example, 'MainChild' and 'AuxChild' are siblings. * When navigating to 'parent/10/(a//aux:b)', the route instantiates * the main child and aux child components next to each other. * For this to work, the application component must have the primary and aux outlets defined. * * ``` * [{ * path: 'parent/:id', * children: [ * { path: 'a', component: MainChild }, * { path: 'b', component: AuxChild, outlet: 'aux' } * ] * }] * ``` * * The router merges the parameters, data, and resolve of the componentless * parent into the parameters, data, and resolve of the children. * * This is especially useful when child components are defined * with an empty path string, as in the following example. * With this configuration, navigating to '/parent/10' creates * the main child and aux components. * * ``` * [{ * path: 'parent/:id', * children: [ * { path: '', component: MainChild }, * { path: '', component: AuxChild, outlet: 'aux' } * ] * }] * ``` * * ### Lazy Loading * * Lazy loading speeds up application load time by splitting the application * into multiple bundles and loading them on demand. * To use lazy loading, provide the `loadChildren` property in the `Route` object, * instead of the `children` property. * * Given the following example route, the router will lazy load * the associated module on demand using the browser native import system. * * ``` * [{ * path: 'lazy', * loadChildren: () => import('./lazy-route/lazy.module').then(mod => mod.LazyModule), * }]; * ``` * * @publicApi */
{ "end_byte": 17056, "start_byte": 10753, "url": "https://github.com/angular/angular/blob/main/packages/router/src/models.ts" }
angular/packages/router/src/models.ts_17057_24579
export interface Route { /** * Used to define a page title for the route. This can be a static string or an `Injectable` that * implements `Resolve`. * * @see {@link TitleStrategy} */ title?: string | Type<Resolve<string>> | ResolveFn<string>; /** * The path to match against. Cannot be used together with a custom `matcher` function. * A URL string that uses router matching notation. * Can be a wild card (`**`) that matches any URL (see Usage Notes below). * Default is "/" (the root path). * */ path?: string; /** * The path-matching strategy, one of 'prefix' or 'full'. * Default is 'prefix'. * * By default, the router checks URL elements from the left to see if the URL * matches a given path and stops when there is a config match. Importantly there must still be a * config match for each segment of the URL. For example, '/team/11/user' matches the prefix * 'team/:id' if one of the route's children matches the segment 'user'. That is, the URL * '/team/11/user' matches the config * `{path: 'team/:id', children: [{path: ':user', component: User}]}` * but does not match when there are no children as in `{path: 'team/:id', component: Team}`. * * The path-match strategy 'full' matches against the entire URL. * It is important to do this when redirecting empty-path routes. * Otherwise, because an empty path is a prefix of any URL, * the router would apply the redirect even when navigating * to the redirect destination, creating an endless loop. * */ pathMatch?: 'prefix' | 'full'; /** * A custom URL-matching function. Cannot be used together with `path`. */ matcher?: UrlMatcher; /** * The component to instantiate when the path matches. * Can be empty if child routes specify components. */ component?: Type<any>; /** * An object specifying a lazy-loaded component. */ loadComponent?: () => | Type<unknown> | Observable<Type<unknown> | DefaultExport<Type<unknown>>> | Promise<Type<unknown> | DefaultExport<Type<unknown>>>; /** * Filled for routes `loadComponent` once the component is loaded. * @internal */ _loadedComponent?: Type<unknown>; /** * A URL or function that returns a URL to redirect to when the path matches. * * Absolute if the URL begins with a slash (/) or the function returns a `UrlTree`, otherwise * relative to the path URL. * * The `RedirectFunction` is run in an injection context so it can call `inject` to get any * required dependencies. * * When not present, router does not redirect. */ redirectTo?: string | RedirectFunction; /** * Name of a `RouterOutlet` object where the component can be placed * when the path matches. */ outlet?: string; /** * An array of `CanActivateFn` or DI tokens used to look up `CanActivate()` * handlers, in order to determine if the current user is allowed to * activate the component. By default, any user can activate. * * When using a function rather than DI tokens, the function can call `inject` to get any required * dependencies. This `inject` call must be done in a synchronous context. */ canActivate?: Array<CanActivateFn | DeprecatedGuard>; /** * An array of `CanMatchFn` or DI tokens used to look up `CanMatch()` * handlers, in order to determine if the current user is allowed to * match the `Route`. By default, any route can match. * * When using a function rather than DI tokens, the function can call `inject` to get any required * dependencies. This `inject` call must be done in a synchronous context. */ canMatch?: Array<CanMatchFn | DeprecatedGuard>; /** * An array of `CanActivateChildFn` or DI tokens used to look up `CanActivateChild()` handlers, * in order to determine if the current user is allowed to activate * a child of the component. By default, any user can activate a child. * * When using a function rather than DI tokens, the function can call `inject` to get any required * dependencies. This `inject` call must be done in a synchronous context. */ canActivateChild?: Array<CanActivateChildFn | DeprecatedGuard>; /** * An array of `CanDeactivateFn` or DI tokens used to look up `CanDeactivate()` * handlers, in order to determine if the current user is allowed to * deactivate the component. By default, any user can deactivate. * * When using a function rather than DI tokens, the function can call `inject` to get any required * dependencies. This `inject` call must be done in a synchronous context. */ canDeactivate?: Array<CanDeactivateFn<any> | DeprecatedGuard>; /** * An array of `CanLoadFn` or DI tokens used to look up `CanLoad()` * handlers, in order to determine if the current user is allowed to * load the component. By default, any user can load. * * When using a function rather than DI tokens, the function can call `inject` to get any required * dependencies. This `inject` call must be done in a synchronous context. * @deprecated Use `canMatch` instead */ canLoad?: Array<CanLoadFn | DeprecatedGuard>; /** * Additional developer-defined data provided to the component via * `ActivatedRoute`. By default, no additional data is passed. */ data?: Data; /** * A map of DI tokens used to look up data resolvers. See `Resolve`. */ resolve?: ResolveData; /** * An array of child `Route` objects that specifies a nested route * configuration. */ children?: Routes; /** * An object specifying lazy-loaded child routes. */ loadChildren?: LoadChildren; /** * A policy for when to run guards and resolvers on a route. * * Guards and/or resolvers will always run when a route is activated or deactivated. When a route * is unchanged, the default behavior is the same as `paramsChange`. * * `paramsChange` : Rerun the guards and resolvers when path or * path param changes. This does not include query parameters. This option is the default. * - `always` : Run on every execution. * - `pathParamsChange` : Rerun guards and resolvers when the path params * change. This does not compare matrix or query parameters. * - `paramsOrQueryParamsChange` : Run when path, matrix, or query parameters change. * - `pathParamsOrQueryParamsChange` : Rerun guards and resolvers when the path params * change or query params have changed. This does not include matrix parameters. * * @see {@link RunGuardsAndResolvers} */ runGuardsAndResolvers?: RunGuardsAndResolvers; /** * A `Provider` array to use for this `Route` and its `children`. * * The `Router` will create a new `EnvironmentInjector` for this * `Route` and use it for this `Route` and its `children`. If this * route also has a `loadChildren` function which returns an `NgModuleRef`, this injector will be * used as the parent of the lazy loaded module. */ providers?: Array<Provider | EnvironmentProviders>; /** * Injector created from the static route providers * @internal */ _injector?: EnvironmentInjector; /** * Filled for routes with `loadChildren` once the routes are loaded. * @internal */ _loadedRoutes?: Route[]; /** * Filled for routes with `loadChildren` once the routes are loaded * @internal */ _loadedInjector?: EnvironmentInjector; } export interface LoadedRouterConfig { routes: Route[]; injector: EnvironmentInjector | undefined; }
{ "end_byte": 24579, "start_byte": 17057, "url": "https://github.com/angular/angular/blob/main/packages/router/src/models.ts" }
angular/packages/router/src/models.ts_24581_32904
/** * @description * * Interface that a class can implement to be a guard deciding if a route can be activated. * If all guards return `true`, navigation continues. If any guard returns `false`, * navigation is cancelled. If any guard returns a `UrlTree`, the current navigation * is cancelled and a new navigation begins to the `UrlTree` returned from the guard. * * The following example implements a `CanActivate` function that checks whether the * current user has permission to activate the requested route. * * ``` * class UserToken {} * class Permissions { * canActivate(): boolean { * return true; * } * } * * @Injectable() * class CanActivateTeam implements CanActivate { * constructor(private permissions: Permissions, private currentUser: UserToken) {} * * canActivate( * route: ActivatedRouteSnapshot, * state: RouterStateSnapshot * ): MaybeAsync<GuardResult> { * return this.permissions.canActivate(this.currentUser, route.params.id); * } * } * ``` * * Here, the defined guard function is provided as part of the `Route` object * in the router configuration: * * ``` * @NgModule({ * imports: [ * RouterModule.forRoot([ * { * path: 'team/:id', * component: TeamComponent, * canActivate: [CanActivateTeam] * } * ]) * ], * providers: [CanActivateTeam, UserToken, Permissions] * }) * class AppModule {} * ``` * * @publicApi */ export interface CanActivate { canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): MaybeAsync<GuardResult>; } /** * The signature of a function used as a `canActivate` guard on a `Route`. * * If all guards return `true`, navigation continues. If any guard returns `false`, * navigation is cancelled. If any guard returns a `UrlTree`, the current navigation * is cancelled and a new navigation begins to the `UrlTree` returned from the guard. * * The following example implements and uses a `CanActivateFn` that checks whether the * current user has permission to activate the requested route. * * ```ts * @Injectable() * class UserToken {} * * @Injectable() * class PermissionsService { * canActivate(currentUser: UserToken, userId: string): boolean { * return true; * } * canMatch(currentUser: UserToken): boolean { * return true; * } * } * * const canActivateTeam: CanActivateFn = ( * route: ActivatedRouteSnapshot, * state: RouterStateSnapshot, * ) => { * return inject(PermissionsService).canActivate(inject(UserToken), route.params['id']); * }; * ``` * * Here, the defined guard function is provided as part of the `Route` object * in the router configuration: * * ```ts * bootstrapApplication(App, { * providers: [ * provideRouter([ * { * path: 'team/:id', * component: TeamComponent, * canActivate: [canActivateTeam], * }, * ]), * ], * }); * ``` * * @publicApi * @see {@link Route} */ export type CanActivateFn = ( route: ActivatedRouteSnapshot, state: RouterStateSnapshot, ) => MaybeAsync<GuardResult>; /** * @description * * Interface that a class can implement to be a guard deciding if a child route can be activated. * If all guards return `true`, navigation continues. If any guard returns `false`, * navigation is cancelled. If any guard returns a `UrlTree`, current navigation * is cancelled and a new navigation begins to the `UrlTree` returned from the guard. * * The following example implements a `CanActivateChild` function that checks whether the * current user has permission to activate the requested child route. * * ``` * class UserToken {} * class Permissions { * canActivate(user: UserToken, id: string): boolean { * return true; * } * } * * @Injectable() * class CanActivateTeam implements CanActivateChild { * constructor(private permissions: Permissions, private currentUser: UserToken) {} * * canActivateChild( * route: ActivatedRouteSnapshot, * state: RouterStateSnapshot * ): MaybeAsync<GuardResult> { * return this.permissions.canActivate(this.currentUser, route.params.id); * } * } * ``` * * Here, the defined guard function is provided as part of the `Route` object * in the router configuration: * * ``` * @NgModule({ * imports: [ * RouterModule.forRoot([ * { * path: 'root', * canActivateChild: [CanActivateTeam], * children: [ * { * path: 'team/:id', * component: TeamComponent * } * ] * } * ]) * ], * providers: [CanActivateTeam, UserToken, Permissions] * }) * class AppModule {} * ``` * * @publicApi */ export interface CanActivateChild { canActivateChild( childRoute: ActivatedRouteSnapshot, state: RouterStateSnapshot, ): MaybeAsync<GuardResult>; } /** * The signature of a function used as a `canActivateChild` guard on a `Route`. * * If all guards return `true`, navigation continues. If any guard returns `false`, * navigation is cancelled. If any guard returns a `UrlTree`, the current navigation * is cancelled and a new navigation begins to the `UrlTree` returned from the guard. * * The following example implements a `canActivate` function that checks whether the * current user has permission to activate the requested route. * * {@example router/route_functional_guards.ts region="CanActivateChildFn"} * * @publicApi * @see {@link Route} */ export type CanActivateChildFn = ( childRoute: ActivatedRouteSnapshot, state: RouterStateSnapshot, ) => MaybeAsync<GuardResult>; /** * @description * * Interface that a class can implement to be a guard deciding if a route can be deactivated. * If all guards return `true`, navigation continues. If any guard returns `false`, * navigation is cancelled. If any guard returns a `UrlTree`, current navigation * is cancelled and a new navigation begins to the `UrlTree` returned from the guard. * * The following example implements a `CanDeactivate` function that checks whether the * current user has permission to deactivate the requested route. * * ``` * class UserToken {} * class Permissions { * canDeactivate(user: UserToken, id: string): boolean { * return true; * } * } * ``` * * Here, the defined guard function is provided as part of the `Route` object * in the router configuration: * * ``` * * @Injectable() * class CanDeactivateTeam implements CanDeactivate<TeamComponent> { * constructor(private permissions: Permissions, private currentUser: UserToken) {} * * canDeactivate( * component: TeamComponent, * currentRoute: ActivatedRouteSnapshot, * currentState: RouterStateSnapshot, * nextState: RouterStateSnapshot * ): MaybeAsync<GuardResult> { * return this.permissions.canDeactivate(this.currentUser, route.params.id); * } * } * * @NgModule({ * imports: [ * RouterModule.forRoot([ * { * path: 'team/:id', * component: TeamComponent, * canDeactivate: [CanDeactivateTeam] * } * ]) * ], * providers: [CanDeactivateTeam, UserToken, Permissions] * }) * class AppModule {} * ``` * * @publicApi */ export interface CanDeactivate<T> { canDeactivate( component: T, currentRoute: ActivatedRouteSnapshot, currentState: RouterStateSnapshot, nextState: RouterStateSnapshot, ): MaybeAsync<GuardResult>; } /** * The signature of a function used as a `canDeactivate` guard on a `Route`. * * If all guards return `true`, navigation continues. If any guard returns `false`, * navigation is cancelled. If any guard returns a `UrlTree`, the current navigation * is cancelled and a new navigation begins to the `UrlTree` returned from the guard. * * The following example implements and uses a `CanDeactivateFn` that checks whether the * user component has unsaved changes before navigating away from the route. * * {@example router/route_functional_guards.ts region="CanDeactivateFn"} * * @publicApi * @see {@link Route} */ export type CanDeactivateFn<T> = ( component: T, currentRoute: ActivatedRouteSnapshot, currentState: RouterStateSnapshot, nextState: RouterStateSnapshot, ) => MaybeAsync<GuardResult>;
{ "end_byte": 32904, "start_byte": 24581, "url": "https://github.com/angular/angular/blob/main/packages/router/src/models.ts" }
angular/packages/router/src/models.ts_32906_41002
/** * @description * * Interface that a class can implement to be a guard deciding if a `Route` can be matched. * If all guards return `true`, navigation continues and the `Router` will use the `Route` during * activation. If any guard returns `false`, the `Route` is skipped for matching and other `Route` * configurations are processed instead. * * The following example implements a `CanMatch` function that decides whether the * current user has permission to access the users page. * * * ``` * class UserToken {} * class Permissions { * canAccess(user: UserToken, route: Route, segments: UrlSegment[]): boolean { * return true; * } * } * * @Injectable() * class CanMatchTeamSection implements CanMatch { * constructor(private permissions: Permissions, private currentUser: UserToken) {} * * canMatch(route: Route, segments: UrlSegment[]): Observable<boolean>|Promise<boolean>|boolean { * return this.permissions.canAccess(this.currentUser, route, segments); * } * } * ``` * * Here, the defined guard function is provided as part of the `Route` object * in the router configuration: * * ``` * * @NgModule({ * imports: [ * RouterModule.forRoot([ * { * path: 'team/:id', * component: TeamComponent, * loadChildren: () => import('./team').then(mod => mod.TeamModule), * canMatch: [CanMatchTeamSection] * }, * { * path: '**', * component: NotFoundComponent * } * ]) * ], * providers: [CanMatchTeamSection, UserToken, Permissions] * }) * class AppModule {} * ``` * * If the `CanMatchTeamSection` were to return `false`, the router would continue navigating to the * `team/:id` URL, but would load the `NotFoundComponent` because the `Route` for `'team/:id'` * could not be used for a URL match but the catch-all `**` `Route` did instead. * * @publicApi */ export interface CanMatch { canMatch(route: Route, segments: UrlSegment[]): MaybeAsync<GuardResult>; } /** * The signature of a function used as a `canMatch` guard on a `Route`. * * If all guards return `true`, navigation continues and the `Router` will use the `Route` during * activation. If any guard returns `false`, the `Route` is skipped for matching and other `Route` * configurations are processed instead. * * The following example implements and uses a `CanMatchFn` that checks whether the * current user has permission to access the team page. * * {@example router/route_functional_guards.ts region="CanMatchFn"} * * @param route The route configuration. * @param segments The URL segments that have not been consumed by previous parent route evaluations. * * @publicApi * @see {@link Route} */ export type CanMatchFn = (route: Route, segments: UrlSegment[]) => MaybeAsync<GuardResult>; /** * @description * * Interface that classes can implement to be a data provider. * A data provider class can be used with the router to resolve data during navigation. * The interface defines a `resolve()` method that is invoked right after the `ResolveStart` * router event. The router waits for the data to be resolved before the route is finally activated. * * The following example implements a `resolve()` method that retrieves the data * needed to activate the requested route. * * ``` * @Injectable({ providedIn: 'root' }) * export class HeroResolver implements Resolve<Hero> { * constructor(private service: HeroService) {} * * resolve( * route: ActivatedRouteSnapshot, * state: RouterStateSnapshot * ): Observable<Hero>|Promise<Hero>|Hero { * return this.service.getHero(route.paramMap.get('id')); * } * } * ``` * * Here, the defined `resolve()` function is provided as part of the `Route` object * in the router configuration: * * ``` * @NgModule({ * imports: [ * RouterModule.forRoot([ * { * path: 'detail/:id', * component: HeroDetailComponent, * resolve: { * hero: HeroResolver * } * } * ]) * ], * exports: [RouterModule] * }) * export class AppRoutingModule {} * ``` * * And you can access to your resolved data from `HeroComponent`: * * ``` * @Component({ * selector: "app-hero", * templateUrl: "hero.component.html", * }) * export class HeroComponent { * * constructor(private activatedRoute: ActivatedRoute) {} * * ngOnInit() { * this.activatedRoute.data.subscribe(({ hero }) => { * // do something with your resolved data ... * }) * } * * } * ``` * * @usageNotes * * When both guard and resolvers are specified, the resolvers are not executed until * all guards have run and succeeded. * For example, consider the following route configuration: * * ``` * { * path: 'base' * canActivate: [BaseGuard], * resolve: {data: BaseDataResolver} * children: [ * { * path: 'child', * guards: [ChildGuard], * component: ChildComponent, * resolve: {childData: ChildDataResolver} * } * ] * } * ``` * The order of execution is: BaseGuard, ChildGuard, BaseDataResolver, ChildDataResolver. * * @publicApi * @see {@link ResolveFn} */ export interface Resolve<T> { resolve( route: ActivatedRouteSnapshot, state: RouterStateSnapshot, ): MaybeAsync<T | RedirectCommand>; } /** * Function type definition for a data provider. * * A data provider can be used with the router to resolve data during navigation. * The router waits for the data to be resolved before the route is finally activated. * * A resolver can also redirect a `RedirectCommand` and the Angular router will use * it to redirect the current navigation to the new destination. * * @usageNotes * * The following example implements a function that retrieves the data * needed to activate the requested route. * * ```ts * interface Hero { * name: string; * } * @Injectable() * export class HeroService { * getHero(id: string) { * return {name: `Superman-${id}`}; * } * } * * export const heroResolver: ResolveFn<Hero> = ( * route: ActivatedRouteSnapshot, * state: RouterStateSnapshot, * ) => { * return inject(HeroService).getHero(route.paramMap.get('id')!); * }; * * bootstrapApplication(App, { * providers: [ * provideRouter([ * { * path: 'detail/:id', * component: HeroDetailComponent, * resolve: {hero: heroResolver}, * }, * ]), * ], * }); * ``` * * And you can access to your resolved data from `HeroComponent`: * * ```ts * @Component({template: ''}) * export class HeroDetailComponent { * private activatedRoute = inject(ActivatedRoute); * * ngOnInit() { * this.activatedRoute.data.subscribe(({hero}) => { * // do something with your resolved data ... * }); * } * } * ``` * * If resolved data cannot be retrieved, you may want to redirect the user * to a new page instead: * * ```ts * export const heroResolver: ResolveFn<Hero> = async ( * route: ActivatedRouteSnapshot, * state: RouterStateSnapshot, * ) => { * const router = inject(Router); * const heroService = inject(HeroService); * try { * return await heroService.getHero(route.paramMap.get('id')!); * } catch { * return new RedirectCommand(router.parseUrl('/404')); * } * }; * ``` * * When both guard and resolvers are specified, the resolvers are not executed until * all guards have run and succeeded. * For example, consider the following route configuration: * * ``` * { * path: 'base' * canActivate: [baseGuard], * resolve: {data: baseDataResolver} * children: [ * { * path: 'child', * canActivate: [childGuard], * component: ChildComponent, * resolve: {childData: childDataResolver} * } * ] * } * ``` * The order of execution is: baseGuard, childGuard, baseDataResolver, childDataResolver. * * @publicApi * @see {@link Route} */ export type ResolveFn<T> = ( route: ActivatedRouteSnapshot, state: RouterStateSnapshot, ) => MaybeAsync<T | RedirectCommand>;
{ "end_byte": 41002, "start_byte": 32906, "url": "https://github.com/angular/angular/blob/main/packages/router/src/models.ts" }
angular/packages/router/src/models.ts_41004_48033
/** * @description * * Interface that a class can implement to be a guard deciding if children can be loaded. * If all guards return `true`, navigation continues. If any guard returns `false`, * navigation is cancelled. If any guard returns a `UrlTree`, current navigation * is cancelled and a new navigation starts to the `UrlTree` returned from the guard. * * The following example implements a `CanLoad` function that decides whether the * current user has permission to load requested child routes. * * * ``` * class UserToken {} * class Permissions { * canLoadChildren(user: UserToken, id: string, segments: UrlSegment[]): boolean { * return true; * } * } * * @Injectable() * class CanLoadTeamSection implements CanLoad { * constructor(private permissions: Permissions, private currentUser: UserToken) {} * * canLoad(route: Route, segments: UrlSegment[]): Observable<boolean>|Promise<boolean>|boolean { * return this.permissions.canLoadChildren(this.currentUser, route, segments); * } * } * ``` * * Here, the defined guard function is provided as part of the `Route` object * in the router configuration: * * ``` * * @NgModule({ * imports: [ * RouterModule.forRoot([ * { * path: 'team/:id', * component: TeamComponent, * loadChildren: () => import('./team').then(mod => mod.TeamModule), * canLoad: [CanLoadTeamSection] * } * ]) * ], * providers: [CanLoadTeamSection, UserToken, Permissions] * }) * class AppModule {} * ``` * * @publicApi * @deprecated Use {@link CanMatch} instead */ export interface CanLoad { canLoad(route: Route, segments: UrlSegment[]): MaybeAsync<GuardResult>; } /** * The signature of a function used as a `canLoad` guard on a `Route`. * * @publicApi * @see {@link CanLoad} * @see {@link Route} * @see {@link CanMatch} * @deprecated Use `Route.canMatch` and `CanMatchFn` instead */ export type CanLoadFn = (route: Route, segments: UrlSegment[]) => MaybeAsync<GuardResult>; /** * @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 {@link Router#navigate} * @see {@link Router#navigateByUrl} * @see [Routing and Navigation guide](guide/routing/common-router-tasks) * * @publicApi */ export interface NavigationBehaviorOptions { /** * How to handle a navigation request to the current URL. * * This value is a subset of the options available in `OnSameUrlNavigation` and * will take precedence over the default value set for the `Router`. * * @see {@link OnSameUrlNavigation} * @see {@link RouterConfigOptions} */ onSameUrlNavigation?: OnSameUrlNavigation; /** * 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}; /** * Use this to convey transient information about this particular navigation, such as how it * happened. In this way, it's different from the persisted value `state` that will be set to * `history.state`. This object is assigned directly to the Router's current `Navigation` * (it is not copied or cloned), so it should be mutated with caution. * * One example of how this might be used is to trigger different single-page navigation animations * depending on how a certain route was reached. For example, consider a photo gallery app, where * you can reach the same photo URL and state via various routes: * * - Clicking on it in a gallery view * - Clicking * - "next" or "previous" when viewing another photo in the album * - Etc. * * Each of these wants a different animation at navigate time. This information doesn't make sense * to store in the persistent URL or history entry state, but it's still important to communicate * from the rest of the application, into the router. * * This information could be used in coordination with the View Transitions feature and the * `onViewTransitionCreated` callback. The information might be used in the callback to set * classes on the document in order to control the transition animations and remove the classes * when the transition has finished animating. */ readonly info?: unknown; /** * When set, the Router will update the browser's address bar to match the given `UrlTree` instead * of the one used for route matching. * * * @usageNotes * * This feature is useful for redirects, such as redirecting to an error page, without changing * the value that will be displayed in the browser's address bar. * * ``` * const canActivate: CanActivateFn = (route: ActivatedRouteSnapshot) => { * const userService = inject(UserService); * const router = inject(Router); * if (!userService.isLoggedIn()) { * const targetOfCurrentNavigation = router.getCurrentNavigation()?.finalUrl; * const redirect = router.parseUrl('/404'); * return new RedirectCommand(redirect, {browserUrl: targetOfCurrentNavigation}); * } * return true; * }; * ``` * * This value is used directly, without considering any `UrlHandingStrategy`. In this way, * `browserUrl` can also be used to use a different value for the browser URL than what would have * been produced by from the navigation due to `UrlHandlingStrategy.merge`. * * This value only affects the path presented in the browser's address bar. It does not apply to * the internal `Router` state. Information such as `params` and `data` will match the internal * state used to match routes which will be different from the browser URL when using this feature * The same is true when using other APIs that cause the browser URL the differ from the Router * state, such as `skipLocationChange`. */ readonly browserUrl?: UrlTree | string; }
{ "end_byte": 48033, "start_byte": 41004, "url": "https://github.com/angular/angular/blob/main/packages/router/src/models.ts" }
angular/packages/router/src/version.ts_0_417
/** * @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.dev/license */ /** * @module * @description * Entry point for all public APIs of the router package. */ import {Version} from '@angular/core'; /** * @publicApi */ export const VERSION = new Version('0.0.0-PLACEHOLDER');
{ "end_byte": 417, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/router/src/version.ts" }
angular/packages/router/src/router_devtools.ts_0_464
/** * @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 {ɵpublishExternalGlobalUtil} from '@angular/core'; import {Route} from './models'; export function getLoadedRoutes(route: Route): Route[] | undefined { return route._loadedRoutes; } ɵpublishExternalGlobalUtil('ɵgetLoadedRoutes', getLoadedRoutes);
{ "end_byte": 464, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/router/src/router_devtools.ts" }
angular/packages/router/src/router_module.ts_0_8886
/** * @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.dev/license */ import { HashLocationStrategy, Location, LocationStrategy, PathLocationStrategy, ViewportScroller, } from '@angular/common'; import { APP_BOOTSTRAP_LISTENER, ComponentRef, inject, Inject, InjectionToken, ModuleWithProviders, NgModule, NgZone, Optional, Provider, SkipSelf, ɵRuntimeError as RuntimeError, } from '@angular/core'; import {EmptyOutletComponent} from './components/empty_outlet'; import {RouterLink} from './directives/router_link'; import {RouterLinkActive} from './directives/router_link_active'; import {RouterOutlet} from './directives/router_outlet'; import {RuntimeErrorCode} from './errors'; import {Routes} from './models'; import {NAVIGATION_ERROR_HANDLER, NavigationTransitions} from './navigation_transition'; import { getBootstrapListener, rootRoute, ROUTER_IS_PROVIDED, withComponentInputBinding, withDebugTracing, withDisabledInitialNavigation, withEnabledBlockingInitialNavigation, withPreloading, withViewTransitions, } from './provide_router'; import {Router} from './router'; import {ExtraOptions, ROUTER_CONFIGURATION} from './router_config'; import {RouterConfigLoader, ROUTES} from './router_config_loader'; import {ChildrenOutletContexts} from './router_outlet_context'; import {ROUTER_SCROLLER, RouterScroller} from './router_scroller'; import {ActivatedRoute} from './router_state'; import {DefaultUrlSerializer, UrlSerializer} from './url_tree'; /** * The directives defined in the `RouterModule`. */ const ROUTER_DIRECTIVES = [RouterOutlet, RouterLink, RouterLinkActive, EmptyOutletComponent]; /** * @docsNotRequired */ export const ROUTER_FORROOT_GUARD = new InjectionToken<void>( typeof ngDevMode === 'undefined' || ngDevMode ? 'router duplicate forRoot guard' : 'ROUTER_FORROOT_GUARD', ); // TODO(atscott): All of these except `ActivatedRoute` are `providedIn: 'root'`. They are only kept // here to avoid a breaking change whereby the provider order matters based on where the // `RouterModule`/`RouterTestingModule` is imported. These can/should be removed as a "breaking" // change in a major version. export const ROUTER_PROVIDERS: Provider[] = [ Location, {provide: UrlSerializer, useClass: DefaultUrlSerializer}, Router, ChildrenOutletContexts, {provide: ActivatedRoute, useFactory: rootRoute, deps: [Router]}, RouterConfigLoader, // Only used to warn when `provideRoutes` is used without `RouterModule` or `provideRouter`. Can // be removed when `provideRoutes` is removed. typeof ngDevMode === 'undefined' || ngDevMode ? {provide: ROUTER_IS_PROVIDED, useValue: true} : [], ]; /** * @description * * Adds directives and providers for in-app navigation among views defined in an application. * Use the Angular `Router` service to declaratively specify application states and manage state * transitions. * * You can import this NgModule multiple times, once for each lazy-loaded bundle. * However, only one `Router` service can be active. * To ensure this, there are two ways to register routes when importing this module: * * * The `forRoot()` method creates an `NgModule` that contains all the directives, the given * routes, and the `Router` service itself. * * The `forChild()` method creates an `NgModule` that contains all the directives and the given * routes, but does not include the `Router` service. * * @see [Routing and Navigation guide](guide/routing/common-router-tasks) for an * overview of how the `Router` service should be used. * * @publicApi */ @NgModule({ imports: ROUTER_DIRECTIVES, exports: ROUTER_DIRECTIVES, }) export class RouterModule { constructor(@Optional() @Inject(ROUTER_FORROOT_GUARD) guard: any) {} /** * Creates and configures a module with all the router providers and directives. * Optionally sets up an application listener to perform an initial navigation. * * When registering the NgModule at the root, import as follows: * * ``` * @NgModule({ * imports: [RouterModule.forRoot(ROUTES)] * }) * class MyNgModule {} * ``` * * @param routes An array of `Route` objects that define the navigation paths for the application. * @param config An `ExtraOptions` configuration object that controls how navigation is performed. * @return The new `NgModule`. * */ static forRoot(routes: Routes, config?: ExtraOptions): ModuleWithProviders<RouterModule> { return { ngModule: RouterModule, providers: [ ROUTER_PROVIDERS, typeof ngDevMode === 'undefined' || ngDevMode ? config?.enableTracing ? withDebugTracing().ɵproviders : [] : [], {provide: ROUTES, multi: true, useValue: routes}, { provide: ROUTER_FORROOT_GUARD, useFactory: provideForRootGuard, deps: [[Router, new Optional(), new SkipSelf()]], }, config?.errorHandler ? { provide: NAVIGATION_ERROR_HANDLER, useValue: config.errorHandler, } : [], {provide: ROUTER_CONFIGURATION, useValue: config ? config : {}}, config?.useHash ? provideHashLocationStrategy() : providePathLocationStrategy(), provideRouterScroller(), config?.preloadingStrategy ? withPreloading(config.preloadingStrategy).ɵproviders : [], config?.initialNavigation ? provideInitialNavigation(config) : [], config?.bindToComponentInputs ? withComponentInputBinding().ɵproviders : [], config?.enableViewTransitions ? withViewTransitions().ɵproviders : [], provideRouterInitializer(), ], }; } /** * Creates a module with all the router directives and a provider registering routes, * without creating a new Router service. * When registering for submodules and lazy-loaded submodules, create the NgModule as follows: * * ``` * @NgModule({ * imports: [RouterModule.forChild(ROUTES)] * }) * class MyNgModule {} * ``` * * @param routes An array of `Route` objects that define the navigation paths for the submodule. * @return The new NgModule. * */ static forChild(routes: Routes): ModuleWithProviders<RouterModule> { return { ngModule: RouterModule, providers: [{provide: ROUTES, multi: true, useValue: routes}], }; } } /** * For internal use by `RouterModule` only. Note that this differs from `withInMemoryRouterScroller` * because it reads from the `ExtraOptions` which should not be used in the standalone world. */ export function provideRouterScroller(): Provider { return { provide: ROUTER_SCROLLER, useFactory: () => { const viewportScroller = inject(ViewportScroller); const zone = inject(NgZone); const config: ExtraOptions = inject(ROUTER_CONFIGURATION); const transitions = inject(NavigationTransitions); const urlSerializer = inject(UrlSerializer); if (config.scrollOffset) { viewportScroller.setOffset(config.scrollOffset); } return new RouterScroller(urlSerializer, transitions, viewportScroller, zone, config); }, }; } // Note: For internal use only with `RouterModule`. Standalone setup via `provideRouter` should // provide hash location directly via `{provide: LocationStrategy, useClass: HashLocationStrategy}`. function provideHashLocationStrategy(): Provider { return {provide: LocationStrategy, useClass: HashLocationStrategy}; } // Note: For internal use only with `RouterModule`. Standalone setup via `provideRouter` does not // need this at all because `PathLocationStrategy` is the default factory for `LocationStrategy`. function providePathLocationStrategy(): Provider { return {provide: LocationStrategy, useClass: PathLocationStrategy}; } export function provideForRootGuard(router: Router): any { if ((typeof ngDevMode === 'undefined' || ngDevMode) && router) { throw new RuntimeError( RuntimeErrorCode.FOR_ROOT_CALLED_TWICE, `The Router was provided more than once. This can happen if 'forRoot' is used outside of the root injector.` + ` Lazy loaded modules should use RouterModule.forChild() instead.`, ); } return 'guarded'; } // Note: For internal use only with `RouterModule`. Standalone router setup with `provideRouter` // users call `withXInitialNavigation` directly. function provideInitialNavigation(config: Pick<ExtraOptions, 'initialNavigation'>): Provider[] { return [ config.initialNavigation === 'disabled' ? withDisabledInitialNavigation().ɵproviders : [], config.initialNavigation === 'enabledBlocking' ? withEnabledBlockingInitialNavigation().ɵproviders : [], ]; } // TO
{ "end_byte": 8886, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/router/src/router_module.ts" }
angular/packages/router/src/router_module.ts_8888_9629
(atscott): This should not be in the public API /** * A DI token for the router initializer that * is called after the app is bootstrapped. * * @publicApi */ export const ROUTER_INITIALIZER = new InjectionToken<(compRef: ComponentRef<any>) => void>( typeof ngDevMode === 'undefined' || ngDevMode ? 'Router Initializer' : '', ); function provideRouterInitializer(): Provider[] { return [ // ROUTER_INITIALIZER token should be removed. It's public API but shouldn't be. We can just // have `getBootstrapListener` directly attached to APP_BOOTSTRAP_LISTENER. {provide: ROUTER_INITIALIZER, useFactory: getBootstrapListener}, {provide: APP_BOOTSTRAP_LISTENER, multi: true, useExisting: ROUTER_INITIALIZER}, ]; }
{ "end_byte": 9629, "start_byte": 8888, "url": "https://github.com/angular/angular/blob/main/packages/router/src/router_module.ts" }
angular/packages/router/src/page_title_strategy.ts_0_2927
/** * @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.dev/license */ import {inject, Injectable} from '@angular/core'; import {Title} from '@angular/platform-browser'; import {ActivatedRouteSnapshot, RouterStateSnapshot} from './router_state'; import {PRIMARY_OUTLET, RouteTitleKey} from './shared'; /** * Provides a strategy for setting the page title after a router navigation. * * The built-in implementation traverses the router state snapshot and finds the deepest primary * outlet with `title` property. Given the `Routes` below, navigating to * `/base/child(popup:aux)` would result in the document title being set to "child". * ``` * [ * {path: 'base', title: 'base', children: [ * {path: 'child', title: 'child'}, * ], * {path: 'aux', outlet: 'popup', title: 'popupTitle'} * ] * ``` * * This class can be used as a base class for custom title strategies. That is, you can create your * own class that extends the `TitleStrategy`. Note that in the above example, the `title` * from the named outlet is never used. However, a custom strategy might be implemented to * incorporate titles in named outlets. * * @publicApi * @see [Page title guide](guide/routing/common-router-tasks#setting-the-page-title) */ @Injectable({providedIn: 'root', useFactory: () => inject(DefaultTitleStrategy)}) export abstract class TitleStrategy { /** Performs the application title update. */ abstract updateTitle(snapshot: RouterStateSnapshot): void; /** * @returns The `title` of the deepest primary route. */ buildTitle(snapshot: RouterStateSnapshot): string | undefined { let pageTitle: string | undefined; let route: ActivatedRouteSnapshot | undefined = snapshot.root; while (route !== undefined) { pageTitle = this.getResolvedTitleForRoute(route) ?? pageTitle; route = route.children.find((child) => child.outlet === PRIMARY_OUTLET); } return pageTitle; } /** * Given an `ActivatedRouteSnapshot`, returns the final value of the * `Route.title` property, which can either be a static string or a resolved value. */ getResolvedTitleForRoute(snapshot: ActivatedRouteSnapshot) { return snapshot.data[RouteTitleKey]; } } /** * The default `TitleStrategy` used by the router that updates the title using the `Title` service. */ @Injectable({providedIn: 'root'}) export class DefaultTitleStrategy extends TitleStrategy { constructor(readonly title: Title) { super(); } /** * Sets the title of the browser to the given value. * * @param title The `pageTitle` from the deepest primary route. */ override updateTitle(snapshot: RouterStateSnapshot): void { const title = this.buildTitle(snapshot); if (title !== undefined) { this.title.setTitle(title); } } }
{ "end_byte": 2927, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/router/src/page_title_strategy.ts" }
angular/packages/router/src/router_outlet_context.ts_0_2769
/** * @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.dev/license */ import {ComponentRef, EnvironmentInjector, Injectable} from '@angular/core'; import {RouterOutletContract} from './directives/router_outlet'; import {ActivatedRoute} from './router_state'; import {getClosestRouteInjector} from './utils/config'; /** * Store contextual information about a `RouterOutlet` * * @publicApi */ export class OutletContext { outlet: RouterOutletContract | null = null; route: ActivatedRoute | null = null; children: ChildrenOutletContexts; attachRef: ComponentRef<any> | null = null; get injector(): EnvironmentInjector { return getClosestRouteInjector(this.route?.snapshot) ?? this.rootInjector; } constructor(private readonly rootInjector: EnvironmentInjector) { this.children = new ChildrenOutletContexts(this.rootInjector); } } /** * Store contextual information about the children (= nested) `RouterOutlet` * * @publicApi */ @Injectable({providedIn: 'root'}) export class ChildrenOutletContexts { // contexts for child outlets, by name. private contexts = new Map<string, OutletContext>(); /** @nodoc */ constructor(private rootInjector: EnvironmentInjector) {} /** Called when a `RouterOutlet` directive is instantiated */ onChildOutletCreated(childName: string, outlet: RouterOutletContract): void { const context = this.getOrCreateContext(childName); context.outlet = outlet; this.contexts.set(childName, context); } /** * Called when a `RouterOutlet` directive is destroyed. * We need to keep the context as the outlet could be destroyed inside a NgIf and might be * re-created later. */ onChildOutletDestroyed(childName: string): void { const context = this.getContext(childName); if (context) { context.outlet = null; context.attachRef = null; } } /** * Called when the corresponding route is deactivated during navigation. * Because the component get destroyed, all children outlet are destroyed. */ onOutletDeactivated(): Map<string, OutletContext> { const contexts = this.contexts; this.contexts = new Map(); return contexts; } onOutletReAttached(contexts: Map<string, OutletContext>) { this.contexts = contexts; } getOrCreateContext(childName: string): OutletContext { let context = this.getContext(childName); if (!context) { context = new OutletContext(this.rootInjector); this.contexts.set(childName, context); } return context; } getContext(childName: string): OutletContext | null { return this.contexts.get(childName) || null; } }
{ "end_byte": 2769, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/router/src/router_outlet_context.ts" }
angular/packages/router/src/directives/router_link_active.ts_0_8364
/** * @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.dev/license */ import { AfterContentInit, ChangeDetectorRef, ContentChildren, Directive, ElementRef, EventEmitter, Input, OnChanges, OnDestroy, Optional, Output, QueryList, Renderer2, SimpleChanges, } from '@angular/core'; import {from, of, Subscription} from 'rxjs'; import {mergeAll} from 'rxjs/operators'; import {Event, NavigationEnd} from '../events'; import {Router} from '../router'; import {IsActiveMatchOptions} from '../url_tree'; import {RouterLink} from './router_link'; /** * * @description * * Tracks whether the linked route of an element is currently active, and allows you * to specify one or more CSS classes to add to the element when the linked route * is active. * * Use this directive to create a visual distinction for elements associated with an active route. * For example, the following code highlights the word "Bob" when the router * activates the associated route: * * ``` * <a routerLink="/user/bob" routerLinkActive="active-link">Bob</a> * ``` * * Whenever the URL is either '/user' or '/user/bob', the "active-link" class is * added to the anchor tag. If the URL changes, the class is removed. * * You can set more than one class using a space-separated string or an array. * For example: * * ``` * <a routerLink="/user/bob" routerLinkActive="class1 class2">Bob</a> * <a routerLink="/user/bob" [routerLinkActive]="['class1', 'class2']">Bob</a> * ``` * * To add the classes only when the URL matches the link exactly, add the option `exact: true`: * * ``` * <a routerLink="/user/bob" routerLinkActive="active-link" [routerLinkActiveOptions]="{exact: * true}">Bob</a> * ``` * * To directly check the `isActive` status of the link, assign the `RouterLinkActive` * instance to a template variable. * For example, the following checks the status without assigning any CSS classes: * * ``` * <a routerLink="/user/bob" routerLinkActive #rla="routerLinkActive"> * Bob {{ rla.isActive ? '(already open)' : ''}} * </a> * ``` * * You can apply the `RouterLinkActive` directive to an ancestor of linked elements. * For example, the following sets the active-link class on the `<div>` parent tag * when the URL is either '/user/jim' or '/user/bob'. * * ``` * <div routerLinkActive="active-link" [routerLinkActiveOptions]="{exact: true}"> * <a routerLink="/user/jim">Jim</a> * <a routerLink="/user/bob">Bob</a> * </div> * ``` * * The `RouterLinkActive` directive can also be used to set the aria-current attribute * to provide an alternative distinction for active elements to visually impaired users. * * For example, the following code adds the 'active' class to the Home Page link when it is * indeed active and in such case also sets its aria-current attribute to 'page': * * ``` * <a routerLink="/" routerLinkActive="active" ariaCurrentWhenActive="page">Home Page</a> * ``` * * @ngModule RouterModule * * @publicApi */ @Directive({ selector: '[routerLinkActive]', exportAs: 'routerLinkActive', standalone: true, }) export class RouterLinkActive implements OnChanges, OnDestroy, AfterContentInit { @ContentChildren(RouterLink, {descendants: true}) links!: QueryList<RouterLink>; private classes: string[] = []; private routerEventsSubscription: Subscription; private linkInputChangesSubscription?: Subscription; private _isActive = false; get isActive() { return this._isActive; } /** * Options to configure how to determine if the router link is active. * * These options are passed to the `Router.isActive()` function. * * @see {@link Router#isActive} */ @Input() routerLinkActiveOptions: {exact: boolean} | IsActiveMatchOptions = {exact: false}; /** * Aria-current attribute to apply when the router link is active. * * Possible values: `'page'` | `'step'` | `'location'` | `'date'` | `'time'` | `true` | `false`. * * @see {@link https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-current} */ @Input() ariaCurrentWhenActive?: 'page' | 'step' | 'location' | 'date' | 'time' | true | false; /** * * You can use the output `isActiveChange` to get notified each time the link becomes * active or inactive. * * Emits: * true -> Route is active * false -> Route is inactive * * ``` * <a * routerLink="/user/bob" * routerLinkActive="active-link" * (isActiveChange)="this.onRouterLinkActive($event)">Bob</a> * ``` */ @Output() readonly isActiveChange: EventEmitter<boolean> = new EventEmitter(); constructor( private router: Router, private element: ElementRef, private renderer: Renderer2, private readonly cdr: ChangeDetectorRef, @Optional() private link?: RouterLink, ) { this.routerEventsSubscription = router.events.subscribe((s: Event) => { if (s instanceof NavigationEnd) { this.update(); } }); } /** @nodoc */ ngAfterContentInit(): void { // `of(null)` is used to force subscribe body to execute once immediately (like `startWith`). of(this.links.changes, of(null)) .pipe(mergeAll()) .subscribe((_) => { this.update(); this.subscribeToEachLinkOnChanges(); }); } private subscribeToEachLinkOnChanges() { this.linkInputChangesSubscription?.unsubscribe(); const allLinkChanges = [...this.links.toArray(), this.link] .filter((link): link is RouterLink => !!link) .map((link) => link.onChanges); this.linkInputChangesSubscription = from(allLinkChanges) .pipe(mergeAll()) .subscribe((link) => { if (this._isActive !== this.isLinkActive(this.router)(link)) { this.update(); } }); } @Input() set routerLinkActive(data: string[] | string) { const classes = Array.isArray(data) ? data : data.split(' '); this.classes = classes.filter((c) => !!c); } /** @nodoc */ ngOnChanges(changes: SimpleChanges): void { this.update(); } /** @nodoc */ ngOnDestroy(): void { this.routerEventsSubscription.unsubscribe(); this.linkInputChangesSubscription?.unsubscribe(); } private update(): void { if (!this.links || !this.router.navigated) return; queueMicrotask(() => { const hasActiveLinks = this.hasActiveLinks(); this.classes.forEach((c) => { if (hasActiveLinks) { this.renderer.addClass(this.element.nativeElement, c); } else { this.renderer.removeClass(this.element.nativeElement, c); } }); if (hasActiveLinks && this.ariaCurrentWhenActive !== undefined) { this.renderer.setAttribute( this.element.nativeElement, 'aria-current', this.ariaCurrentWhenActive.toString(), ); } else { this.renderer.removeAttribute(this.element.nativeElement, 'aria-current'); } // Only emit change if the active state changed. if (this._isActive !== hasActiveLinks) { this._isActive = hasActiveLinks; this.cdr.markForCheck(); // Emit on isActiveChange after classes are updated this.isActiveChange.emit(hasActiveLinks); } }); } private isLinkActive(router: Router): (link: RouterLink) => boolean { const options: boolean | IsActiveMatchOptions = isActiveMatchOptions( this.routerLinkActiveOptions, ) ? this.routerLinkActiveOptions : // While the types should disallow `undefined` here, it's possible without strict inputs this.routerLinkActiveOptions.exact || false; return (link: RouterLink) => { const urlTree = link.urlTree; return urlTree ? router.isActive(urlTree, options) : false; }; } private hasActiveLinks(): boolean { const isActiveCheckFn = this.isLinkActive(this.router); return (this.link && isActiveCheckFn(this.link)) || this.links.some(isActiveCheckFn); } } /** * Use instead of `'paths' in options` to be compatible with property renaming */ function isActiveMatchOptions( options: {exact: boolean} | IsActiveMatchOptions, ): options is IsActiveMatchOptions { return !!(options as IsActiveMatchOptions).paths; }
{ "end_byte": 8364, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/router/src/directives/router_link_active.ts" }
angular/packages/router/src/directives/router_outlet.ts_0_6361
/** * @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.dev/license */ import { ChangeDetectorRef, ComponentRef, Directive, EnvironmentInjector, EventEmitter, inject, Injectable, InjectionToken, Injector, Input, OnDestroy, OnInit, Output, reflectComponentType, SimpleChanges, ViewContainerRef, ɵRuntimeError as RuntimeError, Signal, input, computed, } from '@angular/core'; import {combineLatest, of, Subscription} from 'rxjs'; import {switchMap} from 'rxjs/operators'; import {RuntimeErrorCode} from '../errors'; import {Data} from '../models'; import {ChildrenOutletContexts} from '../router_outlet_context'; import {ActivatedRoute} from '../router_state'; import {PRIMARY_OUTLET} from '../shared'; /** * An `InjectionToken` provided by the `RouterOutlet` and can be set using the `routerOutletData` * input. * * When unset, this value is `null` by default. * * @usageNotes * * To set the data from the template of the component with `router-outlet`: * ``` * <router-outlet [routerOutletData]="{name: 'Angular'}" /> * ``` * * To read the data in the routed component: * ``` * data = inject(ROUTER_OUTLET_DATA) as Signal<{name: string}>; * ``` * * @publicApi */ export const ROUTER_OUTLET_DATA = new InjectionToken<Signal<unknown | undefined>>( ngDevMode ? 'RouterOutlet data' : '', ); /** * An interface that defines the contract for developing a component outlet for the `Router`. * * An outlet acts as a placeholder that Angular dynamically fills based on the current router state. * * A router outlet should register itself with the `Router` via * `ChildrenOutletContexts#onChildOutletCreated` and unregister with * `ChildrenOutletContexts#onChildOutletDestroyed`. When the `Router` identifies a matched `Route`, * it looks for a registered outlet in the `ChildrenOutletContexts` and activates it. * * @see {@link ChildrenOutletContexts} * @publicApi */ export interface RouterOutletContract { /** * Whether the given outlet is activated. * * An outlet is considered "activated" if it has an active component. */ isActivated: boolean; /** The instance of the activated component or `null` if the outlet is not activated. */ component: Object | null; /** * The `Data` of the `ActivatedRoute` snapshot. */ activatedRouteData: Data; /** * The `ActivatedRoute` for the outlet or `null` if the outlet is not activated. */ activatedRoute: ActivatedRoute | null; /** * Called by the `Router` when the outlet should activate (create a component). */ activateWith(activatedRoute: ActivatedRoute, environmentInjector: EnvironmentInjector): void; /** * A request to destroy the currently activated component. * * When a `RouteReuseStrategy` indicates that an `ActivatedRoute` should be removed but stored for * later re-use rather than destroyed, the `Router` will call `detach` instead. */ deactivate(): void; /** * Called when the `RouteReuseStrategy` instructs to detach the subtree. * * This is similar to `deactivate`, but the activated component should _not_ be destroyed. * Instead, it is returned so that it can be reattached later via the `attach` method. */ detach(): ComponentRef<unknown>; /** * Called when the `RouteReuseStrategy` instructs to re-attach a previously detached subtree. */ attach(ref: ComponentRef<unknown>, activatedRoute: ActivatedRoute): void; /** * Emits an activate event when a new component is instantiated **/ activateEvents?: EventEmitter<unknown>; /** * Emits a deactivate event when a component is destroyed. */ deactivateEvents?: EventEmitter<unknown>; /** * Emits an attached component instance when the `RouteReuseStrategy` instructs to re-attach a * previously detached subtree. **/ attachEvents?: EventEmitter<unknown>; /** * Emits a detached component instance when the `RouteReuseStrategy` instructs to detach the * subtree. */ detachEvents?: EventEmitter<unknown>; /** * Used to indicate that the outlet is able to bind data from the `Router` to the outlet * component's inputs. * * When this is `undefined` or `false` and the developer has opted in to the * feature using `withComponentInputBinding`, a warning will be logged in dev mode if this outlet * is used in the application. */ readonly supportsBindingToComponentInputs?: true; } /** * @description * * Acts as a placeholder that Angular dynamically fills based on the current router state. * * Each outlet can have a unique name, determined by the optional `name` attribute. * The name cannot be set or changed dynamically. If not set, default value is "primary". * * ``` * <router-outlet></router-outlet> * <router-outlet name='left'></router-outlet> * <router-outlet name='right'></router-outlet> * ``` * * Named outlets can be the targets of secondary routes. * The `Route` object for a secondary route has an `outlet` property to identify the target outlet: * * `{path: <base-path>, component: <component>, outlet: <target_outlet_name>}` * * Using named outlets and secondary routes, you can target multiple outlets in * the same `RouterLink` directive. * * The router keeps track of separate branches in a navigation tree for each named outlet and * generates a representation of that tree in the URL. * The URL for a secondary route uses the following syntax to specify both the primary and secondary * routes at the same time: * * `http://base-path/primary-route-path(outlet-name:route-path)` * * A router outlet emits an activate event when a new component is instantiated, * deactivate event when a component is destroyed. * An attached event emits when the `RouteReuseStrategy` instructs the outlet to reattach the * subtree, and the detached event emits when the `RouteReuseStrategy` instructs the outlet to * detach the subtree. * * ``` * <router-outlet * (activate)='onActivate($event)' * (deactivate)='onDeactivate($event)' * (attach)='onAttach($event)' * (detach)='onDetach($event)'></router-outlet> * ``` * * @see {@link RouterLink} * @see {@link Route} * @ngModule RouterModule * * @publicApi */
{ "end_byte": 6361, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/router/src/directives/router_outlet.ts" }
angular/packages/router/src/directives/router_outlet.ts_6362_14632
Directive({ selector: 'router-outlet', exportAs: 'outlet', standalone: true, }) export class RouterOutlet implements OnDestroy, OnInit, RouterOutletContract { private activated: ComponentRef<any> | null = null; /** @internal */ get activatedComponentRef(): ComponentRef<any> | null { return this.activated; } private _activatedRoute: ActivatedRoute | null = null; /** * The name of the outlet * */ @Input() name = PRIMARY_OUTLET; @Output('activate') activateEvents = new EventEmitter<any>(); @Output('deactivate') deactivateEvents = new EventEmitter<any>(); /** * Emits an attached component instance when the `RouteReuseStrategy` instructs to re-attach a * previously detached subtree. **/ @Output('attach') attachEvents = new EventEmitter<unknown>(); /** * Emits a detached component instance when the `RouteReuseStrategy` instructs to detach the * subtree. */ @Output('detach') detachEvents = new EventEmitter<unknown>(); /** * Data that will be provided to the child injector through the `ROUTER_OUTLET_DATA` token. * * When unset, the value of the token is `undefined` by default. */ readonly routerOutletData = input<unknown>(undefined); private parentContexts = inject(ChildrenOutletContexts); private location = inject(ViewContainerRef); private changeDetector = inject(ChangeDetectorRef); private inputBinder = inject(INPUT_BINDER, {optional: true}); /** @nodoc */ readonly supportsBindingToComponentInputs = true; /** @nodoc */ ngOnChanges(changes: SimpleChanges) { if (changes['name']) { const {firstChange, previousValue} = changes['name']; if (firstChange) { // The first change is handled by ngOnInit. Because ngOnChanges doesn't get called when no // input is set at all, we need to centrally handle the first change there. return; } // unregister with the old name if (this.isTrackedInParentContexts(previousValue)) { this.deactivate(); this.parentContexts.onChildOutletDestroyed(previousValue); } // register the new name this.initializeOutletWithName(); } } /** @nodoc */ ngOnDestroy(): void { // Ensure that the registered outlet is this one before removing it on the context. if (this.isTrackedInParentContexts(this.name)) { this.parentContexts.onChildOutletDestroyed(this.name); } this.inputBinder?.unsubscribeFromRouteData(this); } private isTrackedInParentContexts(outletName: string) { return this.parentContexts.getContext(outletName)?.outlet === this; } /** @nodoc */ ngOnInit(): void { this.initializeOutletWithName(); } private initializeOutletWithName() { this.parentContexts.onChildOutletCreated(this.name, this); if (this.activated) { return; } // If the outlet was not instantiated at the time the route got activated we need to populate // the outlet when it is initialized (ie inside a NgIf) const context = this.parentContexts.getContext(this.name); if (context?.route) { if (context.attachRef) { // `attachRef` is populated when there is an existing component to mount this.attach(context.attachRef, context.route); } else { // otherwise the component defined in the configuration is created this.activateWith(context.route, context.injector); } } } get isActivated(): boolean { return !!this.activated; } /** * @returns The currently activated component instance. * @throws An error if the outlet is not activated. */ get component(): Object { if (!this.activated) throw new RuntimeError( RuntimeErrorCode.OUTLET_NOT_ACTIVATED, (typeof ngDevMode === 'undefined' || ngDevMode) && 'Outlet is not activated', ); return this.activated.instance; } get activatedRoute(): ActivatedRoute { if (!this.activated) throw new RuntimeError( RuntimeErrorCode.OUTLET_NOT_ACTIVATED, (typeof ngDevMode === 'undefined' || ngDevMode) && 'Outlet is not activated', ); return this._activatedRoute as ActivatedRoute; } get activatedRouteData(): Data { if (this._activatedRoute) { return this._activatedRoute.snapshot.data; } return {}; } /** * Called when the `RouteReuseStrategy` instructs to detach the subtree */ detach(): ComponentRef<any> { if (!this.activated) throw new RuntimeError( RuntimeErrorCode.OUTLET_NOT_ACTIVATED, (typeof ngDevMode === 'undefined' || ngDevMode) && 'Outlet is not activated', ); this.location.detach(); const cmp = this.activated; this.activated = null; this._activatedRoute = null; this.detachEvents.emit(cmp.instance); return cmp; } /** * Called when the `RouteReuseStrategy` instructs to re-attach a previously detached subtree */ attach(ref: ComponentRef<any>, activatedRoute: ActivatedRoute) { this.activated = ref; this._activatedRoute = activatedRoute; this.location.insert(ref.hostView); this.inputBinder?.bindActivatedRouteToOutletComponent(this); this.attachEvents.emit(ref.instance); } deactivate(): void { if (this.activated) { const c = this.component; this.activated.destroy(); this.activated = null; this._activatedRoute = null; this.deactivateEvents.emit(c); } } activateWith(activatedRoute: ActivatedRoute, environmentInjector: EnvironmentInjector) { if (this.isActivated) { throw new RuntimeError( RuntimeErrorCode.OUTLET_ALREADY_ACTIVATED, (typeof ngDevMode === 'undefined' || ngDevMode) && 'Cannot activate an already activated outlet', ); } this._activatedRoute = activatedRoute; const location = this.location; const snapshot = activatedRoute.snapshot; const component = snapshot.component!; const childContexts = this.parentContexts.getOrCreateContext(this.name).children; const injector = new OutletInjector( activatedRoute, childContexts, location.injector, this.routerOutletData, ); this.activated = location.createComponent(component, { index: location.length, injector, environmentInjector: environmentInjector, }); // Calling `markForCheck` to make sure we will run the change detection when the // `RouterOutlet` is inside a `ChangeDetectionStrategy.OnPush` component. this.changeDetector.markForCheck(); this.inputBinder?.bindActivatedRouteToOutletComponent(this); this.activateEvents.emit(this.activated.instance); } } class OutletInjector implements Injector { /** * This injector has a special handing for the `ActivatedRoute` and * `ChildrenOutletContexts` tokens: it returns corresponding values for those * tokens dynamically. This behavior is different from the regular injector logic, * when we initialize and store a value, which is later returned for all inject * requests. * * In some cases (e.g. when using `@defer`), this dynamic behavior requires special * handling. This function allows to identify an instance of the `OutletInjector` and * create an instance of it without referring to the class itself (so this logic can * be invoked from the `core` package). This helps to retain dynamic behavior for the * mentioned tokens. * * Note: it's a temporary solution and we should explore how to support this case better. */ private __ngOutletInjector(parentInjector: Injector) { return new OutletInjector(this.route, this.childContexts, parentInjector, this.outletData); } constructor( private route: ActivatedRoute, private childContexts: ChildrenOutletContexts, private parent: Injector, private outletData: Signal<unknown>, ) {} get(token: any, notFoundValue?: any): any { if (token === ActivatedRoute) { return this.route; } if (token === ChildrenOutletContexts) { return this.childContexts; } if (token === ROUTER_OUTLET_DATA) { return this.outletData; } return this.parent.get(token, notFoundValue); } } export const INPUT_BINDER = new InjectionToken<RoutedComponentInputBinder>('');
{ "end_byte": 14632, "start_byte": 6362, "url": "https://github.com/angular/angular/blob/main/packages/router/src/directives/router_outlet.ts" }
angular/packages/router/src/directives/router_outlet.ts_14634_17602
** * Injectable used as a tree-shakable provider for opting in to binding router data to component * inputs. * * The RouterOutlet registers itself with this service when an `ActivatedRoute` is attached or * activated. When this happens, the service subscribes to the `ActivatedRoute` observables (params, * queryParams, data) and sets the inputs of the component using `ComponentRef.setInput`. * Importantly, when an input does not have an item in the route data with a matching key, this * input is set to `undefined`. If it were not done this way, the previous information would be * retained if the data got removed from the route (i.e. if a query parameter is removed). * * The `RouterOutlet` should unregister itself when destroyed via `unsubscribeFromRouteData` so that * the subscriptions are cleaned up. */ @Injectable() export class RoutedComponentInputBinder { private outletDataSubscriptions = new Map<RouterOutlet, Subscription>(); bindActivatedRouteToOutletComponent(outlet: RouterOutlet) { this.unsubscribeFromRouteData(outlet); this.subscribeToRouteData(outlet); } unsubscribeFromRouteData(outlet: RouterOutlet) { this.outletDataSubscriptions.get(outlet)?.unsubscribe(); this.outletDataSubscriptions.delete(outlet); } private subscribeToRouteData(outlet: RouterOutlet) { const {activatedRoute} = outlet; const dataSubscription = combineLatest([ activatedRoute.queryParams, activatedRoute.params, activatedRoute.data, ]) .pipe( switchMap(([queryParams, params, data], index) => { data = {...queryParams, ...params, ...data}; // Get the first result from the data subscription synchronously so it's available to // the component as soon as possible (and doesn't require a second change detection). if (index === 0) { return of(data); } // Promise.resolve is used to avoid synchronously writing the wrong data when // two of the Observables in the `combineLatest` stream emit one after // another. return Promise.resolve(data); }), ) .subscribe((data) => { // Outlet may have been deactivated or changed names to be associated with a different // route if ( !outlet.isActivated || !outlet.activatedComponentRef || outlet.activatedRoute !== activatedRoute || activatedRoute.component === null ) { this.unsubscribeFromRouteData(outlet); return; } const mirror = reflectComponentType(activatedRoute.component); if (!mirror) { this.unsubscribeFromRouteData(outlet); return; } for (const {templateName} of mirror.inputs) { outlet.activatedComponentRef.setInput(templateName, data[templateName]); } }); this.outletDataSubscriptions.set(outlet, dataSubscription); } }
{ "end_byte": 17602, "start_byte": 14634, "url": "https://github.com/angular/angular/blob/main/packages/router/src/directives/router_outlet.ts" }
angular/packages/router/src/directives/router_link.ts_0_4605
/** * @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.dev/license */ import {LocationStrategy} from '@angular/common'; import { Attribute, booleanAttribute, Directive, ElementRef, HostBinding, HostListener, Input, OnChanges, OnDestroy, Renderer2, ɵRuntimeError as RuntimeError, SimpleChanges, ɵɵsanitizeUrlOrResourceUrl, } from '@angular/core'; import {Subject, Subscription} from 'rxjs'; import {Event, NavigationEnd} from '../events'; import {QueryParamsHandling} from '../models'; import {Router} from '../router'; import {ActivatedRoute} from '../router_state'; import {Params} from '../shared'; import {isUrlTree, UrlTree} from '../url_tree'; import {RuntimeErrorCode} from '../errors'; /** * @description * * When applied to an element in a template, makes that element a link * that initiates navigation to a route. Navigation opens one or more routed components * in one or more `<router-outlet>` locations on the page. * * Given a route configuration `[{ path: 'user/:name', component: UserCmp }]`, * the following creates a static link to the route: * `<a routerLink="/user/bob">link to user component</a>` * * You can use dynamic values to generate the link. * For a dynamic link, pass an array of path segments, * followed by the params for each segment. * For example, `['/team', teamId, 'user', userName, {details: true}]` * generates a link to `/team/11/user/bob;details=true`. * * Multiple static segments can be merged into one term and combined with dynamic segments. * For example, `['/team/11/user', userName, {details: true}]` * * The input that you provide to the link is treated as a delta to the current URL. * For instance, suppose the current URL is `/user/(box//aux:team)`. * The link `<a [routerLink]="['/user/jim']">Jim</a>` creates the URL * `/user/(jim//aux:team)`. * See {@link Router#createUrlTree} for more information. * * @usageNotes * * You can use absolute or relative paths in a link, set query parameters, * control how parameters are handled, and keep a history of navigation states. * * ### Relative link paths * * The first segment name can be prepended with `/`, `./`, or `../`. * * If the first segment begins with `/`, the router looks up the route from the root of the * app. * * If the first segment begins with `./`, or doesn't begin with a slash, the router * looks in the children of the current activated route. * * If the first segment begins with `../`, the router goes up one level in the route tree. * * ### Setting and handling query params and fragments * * The following link adds a query parameter and a fragment to the generated URL: * * ``` * <a [routerLink]="['/user/bob']" [queryParams]="{debug: true}" fragment="education"> * link to user component * </a> * ``` * By default, the directive constructs the new URL using the given query parameters. * The example generates the link: `/user/bob?debug=true#education`. * * You can instruct the directive to handle query parameters differently * by specifying the `queryParamsHandling` option in the link. * Allowed values are: * * - `'merge'`: Merge the given `queryParams` into the current query params. * - `'preserve'`: Preserve the current query params. * * For example: * * ``` * <a [routerLink]="['/user/bob']" [queryParams]="{debug: true}" queryParamsHandling="merge"> * link to user component * </a> * ``` * * `queryParams`, `fragment`, `queryParamsHandling`, `preserveFragment`, and `relativeTo` * cannot be used when the `routerLink` input is a `UrlTree`. * * See {@link UrlCreationOptions#queryParamsHandling}. * * ### Preserving navigation history * * You can provide a `state` value to be persisted to the browser's * [`History.state` property](https://developer.mozilla.org/en-US/docs/Web/API/History#Properties). * For example: * * ``` * <a [routerLink]="['/user/bob']" [state]="{tracingId: 123}"> * link to user component * </a> * ``` * * Use {@link Router#getCurrentNavigation} to retrieve a saved * navigation-state value. For example, to capture the `tracingId` during the `NavigationStart` * event: * * ``` * // Get NavigationStart events * router.events.pipe(filter(e => e instanceof NavigationStart)).subscribe(e => { * const navigation = router.getCurrentNavigation(); * tracingService.trace({id: navigation.extras.state.tracingId}); * }); * ``` * * @ngModule RouterModule * * @publicApi */ @D
{ "end_byte": 4605, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/router/src/directives/router_link.ts" }
angular/packages/router/src/directives/router_link.ts_4606_11787
rective({ selector: '[routerLink]', standalone: true, }) export class RouterLink implements OnChanges, OnDestroy { /** * Represents an `href` attribute value applied to a host element, * when a host element is `<a>`. For other tags, the value is `null`. */ href: string | null = null; /** * Represents the `target` attribute on a host element. * This is only used when the host element is an `<a>` tag. */ @HostBinding('attr.target') @Input() target?: string; /** * Passed to {@link Router#createUrlTree} as part of the * `UrlCreationOptions`. * @see {@link UrlCreationOptions#queryParams} * @see {@link Router#createUrlTree} */ @Input() queryParams?: Params | null; /** * Passed to {@link Router#createUrlTree} as part of the * `UrlCreationOptions`. * @see {@link UrlCreationOptions#fragment} * @see {@link Router#createUrlTree} */ @Input() fragment?: string; /** * Passed to {@link Router#createUrlTree} as part of the * `UrlCreationOptions`. * @see {@link UrlCreationOptions#queryParamsHandling} * @see {@link Router#createUrlTree} */ @Input() queryParamsHandling?: QueryParamsHandling | null; /** * Passed to {@link Router#navigateByUrl} as part of the * `NavigationBehaviorOptions`. * @see {@link NavigationBehaviorOptions#state} * @see {@link Router#navigateByUrl} */ @Input() state?: {[k: string]: any}; /** * Passed to {@link Router#navigateByUrl} as part of the * `NavigationBehaviorOptions`. * @see {@link NavigationBehaviorOptions#info} * @see {@link Router#navigateByUrl} */ @Input() info?: unknown; /** * Passed to {@link Router#createUrlTree} as part of the * `UrlCreationOptions`. * Specify a value here when you do not want to use the default value * for `routerLink`, which is the current activated route. * Note that a value of `undefined` here will use the `routerLink` default. * @see {@link UrlCreationOptions#relativeTo} * @see {@link Router#createUrlTree} */ @Input() relativeTo?: ActivatedRoute | null; /** Whether a host element is an `<a>` tag. */ private isAnchorElement: boolean; private subscription?: Subscription; /** @internal */ onChanges = new Subject<RouterLink>(); constructor( private router: Router, private route: ActivatedRoute, @Attribute('tabindex') private readonly tabIndexAttribute: string | null | undefined, private readonly renderer: Renderer2, private readonly el: ElementRef, private locationStrategy?: LocationStrategy, ) { const tagName = el.nativeElement.tagName?.toLowerCase(); this.isAnchorElement = tagName === 'a' || tagName === 'area'; if (this.isAnchorElement) { this.subscription = router.events.subscribe((s: Event) => { if (s instanceof NavigationEnd) { this.updateHref(); } }); } else { this.setTabIndexIfNotOnNativeEl('0'); } } /** * Passed to {@link Router#createUrlTree} as part of the * `UrlCreationOptions`. * @see {@link UrlCreationOptions#preserveFragment} * @see {@link Router#createUrlTree} */ @Input({transform: booleanAttribute}) preserveFragment: boolean = false; /** * Passed to {@link Router#navigateByUrl} as part of the * `NavigationBehaviorOptions`. * @see {@link NavigationBehaviorOptions#skipLocationChange} * @see {@link Router#navigateByUrl} */ @Input({transform: booleanAttribute}) skipLocationChange: boolean = false; /** * Passed to {@link Router#navigateByUrl} as part of the * `NavigationBehaviorOptions`. * @see {@link NavigationBehaviorOptions#replaceUrl} * @see {@link Router#navigateByUrl} */ @Input({transform: booleanAttribute}) replaceUrl: boolean = false; /** * Modifies the tab index if there was not a tabindex attribute on the element during * instantiation. */ private setTabIndexIfNotOnNativeEl(newTabIndex: string | null) { if (this.tabIndexAttribute != null /* both `null` and `undefined` */ || this.isAnchorElement) { return; } this.applyAttributeValue('tabindex', newTabIndex); } /** @nodoc */ // TODO(atscott): Remove changes parameter in major version as a breaking change. ngOnChanges(changes?: SimpleChanges) { if ( ngDevMode && isUrlTree(this.routerLinkInput) && (this.fragment !== undefined || this.queryParams || this.queryParamsHandling || this.preserveFragment || this.relativeTo) ) { throw new RuntimeError( RuntimeErrorCode.INVALID_ROUTER_LINK_INPUTS, 'Cannot configure queryParams or fragment when using a UrlTree as the routerLink input value.', ); } if (this.isAnchorElement) { this.updateHref(); } // This is subscribed to by `RouterLinkActive` so that it knows to update when there are changes // to the RouterLinks it's tracking. this.onChanges.next(this); } private routerLinkInput: any[] | UrlTree | null = null; /** * Commands to pass to {@link Router#createUrlTree} or a `UrlTree`. * - **array**: commands to pass to {@link Router#createUrlTree}. * - **string**: shorthand for array of commands with just the string, i.e. `['/route']` * - **UrlTree**: a `UrlTree` for this link rather than creating one from the commands * and other inputs that correspond to properties of `UrlCreationOptions`. * - **null|undefined**: effectively disables the `routerLink` * @see {@link Router#createUrlTree} */ @Input() set routerLink(commandsOrUrlTree: any[] | string | UrlTree | null | undefined) { if (commandsOrUrlTree == null) { this.routerLinkInput = null; this.setTabIndexIfNotOnNativeEl(null); } else { if (isUrlTree(commandsOrUrlTree)) { this.routerLinkInput = commandsOrUrlTree; } else { this.routerLinkInput = Array.isArray(commandsOrUrlTree) ? commandsOrUrlTree : [commandsOrUrlTree]; } this.setTabIndexIfNotOnNativeEl('0'); } } /** @nodoc */ @HostListener('click', [ '$event.button', '$event.ctrlKey', '$event.shiftKey', '$event.altKey', '$event.metaKey', ]) onClick( button: number, ctrlKey: boolean, shiftKey: boolean, altKey: boolean, metaKey: boolean, ): boolean { const urlTree = this.urlTree; if (urlTree === null) { return true; } if (this.isAnchorElement) { if (button !== 0 || ctrlKey || shiftKey || altKey || metaKey) { return true; } if (typeof this.target === 'string' && this.target != '_self') { return true; } } const extras = { skipLocationChange: this.skipLocationChange, replaceUrl: this.replaceUrl, state: this.state, info: this.info, }; this.router.navigateByUrl(urlTree, extras); // Return `false` for `<a>` elements to prevent default action // and cancel the native behavior, since the navigation is handled // by the Router. return !this.isAnchorElement; } /** @nodoc */ ngOnDestroy(): any { this.subscription?.unsubscribe(); }
{ "end_byte": 11787, "start_byte": 4606, "url": "https://github.com/angular/angular/blob/main/packages/router/src/directives/router_link.ts" }
angular/packages/router/src/directives/router_link.ts_11791_14319
vate updateHref(): void { const urlTree = this.urlTree; this.href = urlTree !== null && this.locationStrategy ? this.locationStrategy?.prepareExternalUrl(this.router.serializeUrl(urlTree)) : null; const sanitizedValue = this.href === null ? null : // This class represents a directive that can be added to both `<a>` elements, // as well as other elements. As a result, we can't define security context at // compile time. So the security context is deferred to runtime. // The `ɵɵsanitizeUrlOrResourceUrl` selects the necessary sanitizer function // based on the tag and property names. The logic mimics the one from // `packages/compiler/src/schema/dom_security_schema.ts`, which is used at compile time. // // Note: we should investigate whether we can switch to using `@HostBinding('attr.href')` // instead of applying a value via a renderer, after a final merge of the // `RouterLinkWithHref` directive. ɵɵsanitizeUrlOrResourceUrl( this.href, this.el.nativeElement.tagName.toLowerCase(), 'href', ); this.applyAttributeValue('href', sanitizedValue); } private applyAttributeValue(attrName: string, attrValue: string | null) { const renderer = this.renderer; const nativeElement = this.el.nativeElement; if (attrValue !== null) { renderer.setAttribute(nativeElement, attrName, attrValue); } else { renderer.removeAttribute(nativeElement, attrName); } } get urlTree(): UrlTree | null { if (this.routerLinkInput === null) { return null; } else if (isUrlTree(this.routerLinkInput)) { return this.routerLinkInput; } return this.router.createUrlTree(this.routerLinkInput, { // If the `relativeTo` input is not defined, we want to use `this.route` by default. // Otherwise, we should use the value provided by the user in the input. relativeTo: this.relativeTo !== undefined ? this.relativeTo : this.route, queryParams: this.queryParams, fragment: this.fragment, queryParamsHandling: this.queryParamsHandling, preserveFragment: this.preserveFragment, }); } } /** * @description * An alias for the `RouterLink` directive. * Deprecated since v15, use `RouterLink` directive instead. * * @deprecated use `RouterLink` directive instead. * @publicApi */ export {RouterLink as RouterLinkWithHref};
{ "end_byte": 14319, "start_byte": 11791, "url": "https://github.com/angular/angular/blob/main/packages/router/src/directives/router_link.ts" }
angular/packages/router/src/operators/prioritized_guard_value.ts_0_1809
/** * @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.dev/license */ import {combineLatest, Observable, OperatorFunction} from 'rxjs'; import {filter, map, startWith, switchMap, take} from 'rxjs/operators'; import {GuardResult, RedirectCommand} from '../models'; import {isUrlTree, UrlTree} from '../url_tree'; const INITIAL_VALUE = /* @__PURE__ */ Symbol('INITIAL_VALUE'); declare type INTERIM_VALUES = typeof INITIAL_VALUE | GuardResult; export function prioritizedGuardValue(): OperatorFunction<Observable<GuardResult>[], GuardResult> { return switchMap((obs) => { return combineLatest( obs.map((o) => o.pipe(take(1), startWith(INITIAL_VALUE as INTERIM_VALUES))), ).pipe( map((results: INTERIM_VALUES[]) => { for (const result of results) { if (result === true) { // If result is true, check the next one continue; } else if (result === INITIAL_VALUE) { // If guard has not finished, we need to stop processing. return INITIAL_VALUE; } else if (result === false || isRedirect(result)) { // Result finished and was not true. Return the result. // Note that we only allow false/UrlTree/RedirectCommand. Other values are considered invalid and // ignored. return result; } } // Everything resolved to true. Return true. return true; }), filter((item): item is GuardResult => item !== INITIAL_VALUE), take(1), ); }); } function isRedirect(val: INTERIM_VALUES): val is UrlTree | RedirectCommand { return isUrlTree(val) || val instanceof RedirectCommand; }
{ "end_byte": 1809, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/router/src/operators/prioritized_guard_value.ts" }
angular/packages/router/src/operators/switch_tap.ts_0_940
/** * @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.dev/license */ import {from, MonoTypeOperatorFunction, ObservableInput, of} from 'rxjs'; import {map, switchMap} from 'rxjs/operators'; /** * Perform a side effect through a switchMap for every emission on the source Observable, * but return an Observable that is identical to the source. It's essentially the same as * the `tap` operator, but if the side effectful `next` function returns an ObservableInput, * it will wait before continuing with the original value. */ export function switchTap<T>( next: (x: T) => void | ObservableInput<any>, ): MonoTypeOperatorFunction<T> { return switchMap((v) => { const nextResult = next(v); if (nextResult) { return from(nextResult).pipe(map(() => v)); } return of(v); }); }
{ "end_byte": 940, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/router/src/operators/switch_tap.ts" }
angular/packages/router/src/operators/activate_routes.ts_0_1277
/** * @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.dev/license */ import {MonoTypeOperatorFunction} from 'rxjs'; import {map} from 'rxjs/operators'; import {ActivationEnd, ChildActivationEnd, Event} from '../events'; import {NavigationTransition} from '../navigation_transition'; import {DetachedRouteHandleInternal, RouteReuseStrategy} from '../route_reuse_strategy'; import {ChildrenOutletContexts} from '../router_outlet_context'; import {ActivatedRoute, advanceActivatedRoute, RouterState} from '../router_state'; import {getClosestRouteInjector} from '../utils/config'; import {nodeChildrenAsMap, TreeNode} from '../utils/tree'; let warnedAboutUnsupportedInputBinding = false; export const activateRoutes = ( rootContexts: ChildrenOutletContexts, routeReuseStrategy: RouteReuseStrategy, forwardEvent: (evt: Event) => void, inputBindingEnabled: boolean, ): MonoTypeOperatorFunction<NavigationTransition> => map((t) => { new ActivateRoutes( routeReuseStrategy, t.targetRouterState!, t.currentRouterState, forwardEvent, inputBindingEnabled, ).activate(rootContexts); return t; });
{ "end_byte": 1277, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/router/src/operators/activate_routes.ts" }
angular/packages/router/src/operators/activate_routes.ts_1279_9844
export class ActivateRoutes { constructor( private routeReuseStrategy: RouteReuseStrategy, private futureState: RouterState, private currState: RouterState, private forwardEvent: (evt: Event) => void, private inputBindingEnabled: boolean, ) {} activate(parentContexts: ChildrenOutletContexts): void { const futureRoot = this.futureState._root; const currRoot = this.currState ? this.currState._root : null; this.deactivateChildRoutes(futureRoot, currRoot, parentContexts); advanceActivatedRoute(this.futureState.root); this.activateChildRoutes(futureRoot, currRoot, parentContexts); } // De-activate the child route that are not re-used for the future state private deactivateChildRoutes( futureNode: TreeNode<ActivatedRoute>, currNode: TreeNode<ActivatedRoute> | null, contexts: ChildrenOutletContexts, ): void { const children: {[outletName: string]: TreeNode<ActivatedRoute>} = nodeChildrenAsMap(currNode); // Recurse on the routes active in the future state to de-activate deeper children futureNode.children.forEach((futureChild) => { const childOutletName = futureChild.value.outlet; this.deactivateRoutes(futureChild, children[childOutletName], contexts); delete children[childOutletName]; }); // De-activate the routes that will not be re-used Object.values(children).forEach((v: TreeNode<ActivatedRoute>) => { this.deactivateRouteAndItsChildren(v, contexts); }); } private deactivateRoutes( futureNode: TreeNode<ActivatedRoute>, currNode: TreeNode<ActivatedRoute>, parentContext: ChildrenOutletContexts, ): void { const future = futureNode.value; const curr = currNode ? currNode.value : null; if (future === curr) { // Reusing the node, check to see if the children need to be de-activated if (future.component) { // If we have a normal route, we need to go through an outlet. const context = parentContext.getContext(future.outlet); if (context) { this.deactivateChildRoutes(futureNode, currNode, context.children); } } else { // if we have a componentless route, we recurse but keep the same outlet map. this.deactivateChildRoutes(futureNode, currNode, parentContext); } } else { if (curr) { // Deactivate the current route which will not be re-used this.deactivateRouteAndItsChildren(currNode, parentContext); } } } private deactivateRouteAndItsChildren( route: TreeNode<ActivatedRoute>, parentContexts: ChildrenOutletContexts, ): void { // If there is no component, the Route is never attached to an outlet (because there is no // component to attach). if (route.value.component && this.routeReuseStrategy.shouldDetach(route.value.snapshot)) { this.detachAndStoreRouteSubtree(route, parentContexts); } else { this.deactivateRouteAndOutlet(route, parentContexts); } } private detachAndStoreRouteSubtree( route: TreeNode<ActivatedRoute>, parentContexts: ChildrenOutletContexts, ): void { const context = parentContexts.getContext(route.value.outlet); const contexts = context && route.value.component ? context.children : parentContexts; const children: {[outletName: string]: TreeNode<ActivatedRoute>} = nodeChildrenAsMap(route); for (const treeNode of Object.values(children)) { this.deactivateRouteAndItsChildren(treeNode, contexts); } if (context && context.outlet) { const componentRef = context.outlet.detach(); const contexts = context.children.onOutletDeactivated(); this.routeReuseStrategy.store(route.value.snapshot, {componentRef, route, contexts}); } } private deactivateRouteAndOutlet( route: TreeNode<ActivatedRoute>, parentContexts: ChildrenOutletContexts, ): void { const context = parentContexts.getContext(route.value.outlet); // The context could be `null` if we are on a componentless route but there may still be // children that need deactivating. const contexts = context && route.value.component ? context.children : parentContexts; const children: {[outletName: string]: TreeNode<ActivatedRoute>} = nodeChildrenAsMap(route); for (const treeNode of Object.values(children)) { this.deactivateRouteAndItsChildren(treeNode, contexts); } if (context) { if (context.outlet) { // Destroy the component context.outlet.deactivate(); // Destroy the contexts for all the outlets that were in the component context.children.onOutletDeactivated(); } // Clear the information about the attached component on the context but keep the reference to // the outlet. Clear even if outlet was not yet activated to avoid activating later with old // info context.attachRef = null; context.route = null; } } private activateChildRoutes( futureNode: TreeNode<ActivatedRoute>, currNode: TreeNode<ActivatedRoute> | null, contexts: ChildrenOutletContexts, ): void { const children: {[outlet: string]: TreeNode<ActivatedRoute>} = nodeChildrenAsMap(currNode); futureNode.children.forEach((c) => { this.activateRoutes(c, children[c.value.outlet], contexts); this.forwardEvent(new ActivationEnd(c.value.snapshot)); }); if (futureNode.children.length) { this.forwardEvent(new ChildActivationEnd(futureNode.value.snapshot)); } } private activateRoutes( futureNode: TreeNode<ActivatedRoute>, currNode: TreeNode<ActivatedRoute>, parentContexts: ChildrenOutletContexts, ): void { const future = futureNode.value; const curr = currNode ? currNode.value : null; advanceActivatedRoute(future); // reusing the node if (future === curr) { if (future.component) { // If we have a normal route, we need to go through an outlet. const context = parentContexts.getOrCreateContext(future.outlet); this.activateChildRoutes(futureNode, currNode, context.children); } else { // if we have a componentless route, we recurse but keep the same outlet map. this.activateChildRoutes(futureNode, currNode, parentContexts); } } else { if (future.component) { // if we have a normal route, we need to place the component into the outlet and recurse. const context = parentContexts.getOrCreateContext(future.outlet); if (this.routeReuseStrategy.shouldAttach(future.snapshot)) { const stored = <DetachedRouteHandleInternal>( this.routeReuseStrategy.retrieve(future.snapshot) ); this.routeReuseStrategy.store(future.snapshot, null); context.children.onOutletReAttached(stored.contexts); context.attachRef = stored.componentRef; context.route = stored.route.value; if (context.outlet) { // Attach right away when the outlet has already been instantiated // Otherwise attach from `RouterOutlet.ngOnInit` when it is instantiated context.outlet.attach(stored.componentRef, stored.route.value); } advanceActivatedRoute(stored.route.value); this.activateChildRoutes(futureNode, null, context.children); } else { context.attachRef = null; context.route = future; if (context.outlet) { // Activate the outlet when it has already been instantiated // Otherwise it will get activated from its `ngOnInit` when instantiated context.outlet.activateWith(future, context.injector); } this.activateChildRoutes(futureNode, null, context.children); } } else { // if we have a componentless route, we recurse but keep the same outlet map. this.activateChildRoutes(futureNode, null, parentContexts); } } if (typeof ngDevMode === 'undefined' || ngDevMode) { const context = parentContexts.getOrCreateContext(future.outlet); const outlet = context.outlet; if ( outlet && this.inputBindingEnabled && !outlet.supportsBindingToComponentInputs && !warnedAboutUnsupportedInputBinding ) { console.warn( `'withComponentInputBinding' feature is enabled but ` + `this application is using an outlet that may not support binding to component inputs.`, ); warnedAboutUnsupportedInputBinding = true; } } } }
{ "end_byte": 9844, "start_byte": 1279, "url": "https://github.com/angular/angular/blob/main/packages/router/src/operators/activate_routes.ts" }
angular/packages/router/src/operators/recognize.ts_0_1248
/** * @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.dev/license */ import {EnvironmentInjector, Type} from '@angular/core'; import {MonoTypeOperatorFunction} from 'rxjs'; import {map, mergeMap} from 'rxjs/operators'; import {Route} from '../models'; import {NavigationTransition} from '../navigation_transition'; import {recognize as recognizeFn} from '../recognize'; import {RouterConfigLoader} from '../router_config_loader'; import {UrlSerializer} from '../url_tree'; export function recognize( injector: EnvironmentInjector, configLoader: RouterConfigLoader, rootComponentType: Type<any> | null, config: Route[], serializer: UrlSerializer, paramsInheritanceStrategy: 'emptyOnly' | 'always', ): MonoTypeOperatorFunction<NavigationTransition> { return mergeMap((t) => recognizeFn( injector, configLoader, rootComponentType, config, t.extractedUrl, serializer, paramsInheritanceStrategy, ).pipe( map(({state: targetSnapshot, tree: urlAfterRedirects}) => { return {...t, targetSnapshot, urlAfterRedirects}; }), ), ); }
{ "end_byte": 1248, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/router/src/operators/recognize.ts" }
angular/packages/router/src/operators/check_guards.ts_0_7809
/** * @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.dev/license */ import {EnvironmentInjector, ProviderToken, runInInjectionContext} from '@angular/core'; import { concat, defer, from, MonoTypeOperatorFunction, Observable, of, OperatorFunction, pipe, } from 'rxjs'; import {concatMap, first, map, mergeMap, tap} from 'rxjs/operators'; import {ActivationStart, ChildActivationStart, Event} from '../events'; import { CanActivateChildFn, CanActivateFn, CanDeactivateFn, GuardResult, CanLoadFn, CanMatchFn, Route, } from '../models'; import {navigationCancelingError, redirectingNavigationError} from '../navigation_canceling_error'; import {NavigationTransition} from '../navigation_transition'; import {ActivatedRouteSnapshot, RouterStateSnapshot} from '../router_state'; import {isUrlTree, UrlSegment, UrlSerializer, UrlTree} from '../url_tree'; import {wrapIntoObservable} from '../utils/collection'; import {getClosestRouteInjector} from '../utils/config'; import { CanActivate, CanDeactivate, getCanActivateChild, getTokenOrFunctionIdentity, } from '../utils/preactivation'; import { isBoolean, isCanActivate, isCanActivateChild, isCanDeactivate, isCanLoad, isCanMatch, } from '../utils/type_guards'; import {prioritizedGuardValue} from './prioritized_guard_value'; export function checkGuards( injector: EnvironmentInjector, forwardEvent?: (evt: Event) => void, ): MonoTypeOperatorFunction<NavigationTransition> { return mergeMap((t) => { const { targetSnapshot, currentSnapshot, guards: {canActivateChecks, canDeactivateChecks}, } = t; if (canDeactivateChecks.length === 0 && canActivateChecks.length === 0) { return of({...t, guardsResult: true}); } return runCanDeactivateChecks( canDeactivateChecks, targetSnapshot!, currentSnapshot, injector, ).pipe( mergeMap((canDeactivate) => { return canDeactivate && isBoolean(canDeactivate) ? runCanActivateChecks(targetSnapshot!, canActivateChecks, injector, forwardEvent) : of(canDeactivate); }), map((guardsResult) => ({...t, guardsResult})), ); }); } function runCanDeactivateChecks( checks: CanDeactivate[], futureRSS: RouterStateSnapshot, currRSS: RouterStateSnapshot, injector: EnvironmentInjector, ) { return from(checks).pipe( mergeMap((check) => runCanDeactivate(check.component, check.route, currRSS, futureRSS, injector), ), first((result) => { return result !== true; }, true), ); } function runCanActivateChecks( futureSnapshot: RouterStateSnapshot, checks: CanActivate[], injector: EnvironmentInjector, forwardEvent?: (evt: Event) => void, ) { return from(checks).pipe( concatMap((check: CanActivate) => { return concat( fireChildActivationStart(check.route.parent, forwardEvent), fireActivationStart(check.route, forwardEvent), runCanActivateChild(futureSnapshot, check.path, injector), runCanActivate(futureSnapshot, check.route, injector), ); }), first((result) => { return result !== true; }, true), ); } /** * This should fire off `ActivationStart` events for each route being activated at this * level. * In other words, if you're activating `a` and `b` below, `path` will contain the * `ActivatedRouteSnapshot`s for both and we will fire `ActivationStart` for both. Always * return * `true` so checks continue to run. */ function fireActivationStart( snapshot: ActivatedRouteSnapshot | null, forwardEvent?: (evt: Event) => void, ): Observable<boolean> { if (snapshot !== null && forwardEvent) { forwardEvent(new ActivationStart(snapshot)); } return of(true); } /** * This should fire off `ChildActivationStart` events for each route being activated at this * level. * In other words, if you're activating `a` and `b` below, `path` will contain the * `ActivatedRouteSnapshot`s for both and we will fire `ChildActivationStart` for both. Always * return * `true` so checks continue to run. */ function fireChildActivationStart( snapshot: ActivatedRouteSnapshot | null, forwardEvent?: (evt: Event) => void, ): Observable<boolean> { if (snapshot !== null && forwardEvent) { forwardEvent(new ChildActivationStart(snapshot)); } return of(true); } function runCanActivate( futureRSS: RouterStateSnapshot, futureARS: ActivatedRouteSnapshot, injector: EnvironmentInjector, ): Observable<GuardResult> { const canActivate = futureARS.routeConfig ? futureARS.routeConfig.canActivate : null; if (!canActivate || canActivate.length === 0) return of(true); const canActivateObservables = canActivate.map( (canActivate: CanActivateFn | ProviderToken<unknown>) => { return defer(() => { const closestInjector = getClosestRouteInjector(futureARS) ?? injector; const guard = getTokenOrFunctionIdentity<CanActivate>(canActivate, closestInjector); const guardVal = isCanActivate(guard) ? guard.canActivate(futureARS, futureRSS) : runInInjectionContext(closestInjector, () => (guard as CanActivateFn)(futureARS, futureRSS), ); return wrapIntoObservable(guardVal).pipe(first()); }); }, ); return of(canActivateObservables).pipe(prioritizedGuardValue()); } function runCanActivateChild( futureRSS: RouterStateSnapshot, path: ActivatedRouteSnapshot[], injector: EnvironmentInjector, ): Observable<GuardResult> { const futureARS = path[path.length - 1]; const canActivateChildGuards = path .slice(0, path.length - 1) .reverse() .map((p) => getCanActivateChild(p)) .filter((_) => _ !== null); const canActivateChildGuardsMapped = canActivateChildGuards.map((d: any) => { return defer(() => { const guardsMapped = d.guards.map( (canActivateChild: CanActivateChildFn | ProviderToken<unknown>) => { const closestInjector = getClosestRouteInjector(d.node) ?? injector; const guard = getTokenOrFunctionIdentity<{canActivateChild: CanActivateChildFn}>( canActivateChild, closestInjector, ); const guardVal = isCanActivateChild(guard) ? guard.canActivateChild(futureARS, futureRSS) : runInInjectionContext(closestInjector, () => (guard as CanActivateChildFn)(futureARS, futureRSS), ); return wrapIntoObservable(guardVal).pipe(first()); }, ); return of(guardsMapped).pipe(prioritizedGuardValue()); }); }); return of(canActivateChildGuardsMapped).pipe(prioritizedGuardValue()); } function runCanDeactivate( component: Object | null, currARS: ActivatedRouteSnapshot, currRSS: RouterStateSnapshot, futureRSS: RouterStateSnapshot, injector: EnvironmentInjector, ): Observable<GuardResult> { const canDeactivate = currARS && currARS.routeConfig ? currARS.routeConfig.canDeactivate : null; if (!canDeactivate || canDeactivate.length === 0) return of(true); const canDeactivateObservables = canDeactivate.map((c: any) => { const closestInjector = getClosestRouteInjector(currARS) ?? injector; const guard = getTokenOrFunctionIdentity<any>(c, closestInjector); const guardVal = isCanDeactivate(guard) ? guard.canDeactivate(component, currARS, currRSS, futureRSS) : runInInjectionContext(closestInjector, () => (guard as CanDeactivateFn<any>)(component, currARS, currRSS, futureRSS), ); return wrapIntoObservable(guardVal).pipe(first()); }); return of(canDeactivateObservables).pipe(prioritizedGuardValue()); }
{ "end_byte": 7809, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/router/src/operators/check_guards.ts" }
angular/packages/router/src/operators/check_guards.ts_7811_9577
export function runCanLoadGuards( injector: EnvironmentInjector, route: Route, segments: UrlSegment[], urlSerializer: UrlSerializer, ): Observable<boolean> { const canLoad = route.canLoad; if (canLoad === undefined || canLoad.length === 0) { return of(true); } const canLoadObservables = canLoad.map((injectionToken: any) => { const guard = getTokenOrFunctionIdentity<any>(injectionToken, injector); const guardVal = isCanLoad(guard) ? guard.canLoad(route, segments) : runInInjectionContext(injector, () => (guard as CanLoadFn)(route, segments)); return wrapIntoObservable(guardVal); }); return of(canLoadObservables).pipe(prioritizedGuardValue(), redirectIfUrlTree(urlSerializer)); } function redirectIfUrlTree(urlSerializer: UrlSerializer): OperatorFunction<GuardResult, boolean> { return pipe( tap((result: GuardResult) => { if (typeof result === 'boolean') return; throw redirectingNavigationError(urlSerializer, result); }), map((result) => result === true), ); } export function runCanMatchGuards( injector: EnvironmentInjector, route: Route, segments: UrlSegment[], urlSerializer: UrlSerializer, ): Observable<GuardResult> { const canMatch = route.canMatch; if (!canMatch || canMatch.length === 0) return of(true); const canMatchObservables = canMatch.map((injectionToken) => { const guard = getTokenOrFunctionIdentity(injectionToken, injector); const guardVal = isCanMatch(guard) ? guard.canMatch(route, segments) : runInInjectionContext(injector, () => (guard as CanMatchFn)(route, segments)); return wrapIntoObservable(guardVal); }); return of(canMatchObservables).pipe(prioritizedGuardValue(), redirectIfUrlTree(urlSerializer)); }
{ "end_byte": 9577, "start_byte": 7811, "url": "https://github.com/angular/angular/blob/main/packages/router/src/operators/check_guards.ts" }
angular/packages/router/src/operators/resolve_data.ts_0_5137
/** * @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.dev/license */ import {EnvironmentInjector, ProviderToken, runInInjectionContext} from '@angular/core'; import {EMPTY, from, MonoTypeOperatorFunction, Observable, of, throwError} from 'rxjs'; import {catchError, concatMap, first, map, mapTo, mergeMap, takeLast, tap} from 'rxjs/operators'; import {RedirectCommand, ResolveData} from '../models'; import {NavigationTransition} from '../navigation_transition'; import { ActivatedRouteSnapshot, getInherited, hasStaticTitle, RouterStateSnapshot, } from '../router_state'; import {RouteTitleKey} from '../shared'; import {getDataKeys, wrapIntoObservable} from '../utils/collection'; import {getClosestRouteInjector} from '../utils/config'; import {getTokenOrFunctionIdentity} from '../utils/preactivation'; import {isEmptyError} from '../utils/type_guards'; import {redirectingNavigationError} from '../navigation_canceling_error'; import {DefaultUrlSerializer} from '../url_tree'; export function resolveData( paramsInheritanceStrategy: 'emptyOnly' | 'always', injector: EnvironmentInjector, ): MonoTypeOperatorFunction<NavigationTransition> { return mergeMap((t) => { const { targetSnapshot, guards: {canActivateChecks}, } = t; if (!canActivateChecks.length) { return of(t); } // Iterating a Set in javascript happens in insertion order so it is safe to use a `Set` to // preserve the correct order that the resolvers should run in. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set#description const routesWithResolversToRun = new Set(canActivateChecks.map((check) => check.route)); const routesNeedingDataUpdates = new Set<ActivatedRouteSnapshot>(); for (const route of routesWithResolversToRun) { if (routesNeedingDataUpdates.has(route)) { continue; } // All children under the route with a resolver to run need to recompute inherited data. for (const newRoute of flattenRouteTree(route)) { routesNeedingDataUpdates.add(newRoute); } } let routesProcessed = 0; return from(routesNeedingDataUpdates).pipe( concatMap((route) => { if (routesWithResolversToRun.has(route)) { return runResolve(route, targetSnapshot!, paramsInheritanceStrategy, injector); } else { route.data = getInherited(route, route.parent, paramsInheritanceStrategy).resolve; return of(void 0); } }), tap(() => routesProcessed++), takeLast(1), mergeMap((_) => (routesProcessed === routesNeedingDataUpdates.size ? of(t) : EMPTY)), ); }); } /** * Returns the `ActivatedRouteSnapshot` tree as an array, using DFS to traverse the route tree. */ function flattenRouteTree(route: ActivatedRouteSnapshot): ActivatedRouteSnapshot[] { const descendants = route.children.map((child) => flattenRouteTree(child)).flat(); return [route, ...descendants]; } function runResolve( futureARS: ActivatedRouteSnapshot, futureRSS: RouterStateSnapshot, paramsInheritanceStrategy: 'emptyOnly' | 'always', injector: EnvironmentInjector, ) { const config = futureARS.routeConfig; const resolve = futureARS._resolve; if (config?.title !== undefined && !hasStaticTitle(config)) { resolve[RouteTitleKey] = config.title; } return resolveNode(resolve, futureARS, futureRSS, injector).pipe( map((resolvedData: any) => { futureARS._resolvedData = resolvedData; futureARS.data = getInherited(futureARS, futureARS.parent, paramsInheritanceStrategy).resolve; return null; }), ); } function resolveNode( resolve: ResolveData, futureARS: ActivatedRouteSnapshot, futureRSS: RouterStateSnapshot, injector: EnvironmentInjector, ): Observable<any> { const keys = getDataKeys(resolve); if (keys.length === 0) { return of({}); } const data: {[k: string | symbol]: any} = {}; return from(keys).pipe( mergeMap((key) => getResolver(resolve[key], futureARS, futureRSS, injector).pipe( first(), tap((value: any) => { if (value instanceof RedirectCommand) { throw redirectingNavigationError(new DefaultUrlSerializer(), value); } data[key] = value; }), ), ), takeLast(1), mapTo(data), catchError((e: unknown) => (isEmptyError(e as Error) ? EMPTY : throwError(e))), ); } function getResolver( injectionToken: ProviderToken<any> | Function, futureARS: ActivatedRouteSnapshot, futureRSS: RouterStateSnapshot, injector: EnvironmentInjector, ): Observable<any> { const closestInjector = getClosestRouteInjector(futureARS) ?? injector; const resolver = getTokenOrFunctionIdentity(injectionToken, closestInjector); const resolverValue = resolver.resolve ? resolver.resolve(futureARS, futureRSS) : runInInjectionContext(closestInjector, () => resolver(futureARS, futureRSS)); return wrapIntoObservable(resolverValue); }
{ "end_byte": 5137, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/router/src/operators/resolve_data.ts" }
angular/packages/router/src/statemanager/state_manager.ts_0_3807
/** * @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.dev/license */ import {Location} from '@angular/common'; import {inject, Injectable} from '@angular/core'; import {SubscriptionLike} from 'rxjs'; import { BeforeActivateRoutes, Event, NavigationCancel, NavigationCancellationCode, NavigationEnd, NavigationError, NavigationSkipped, NavigationStart, PrivateRouterEvents, RoutesRecognized, } from '../events'; import {Navigation, RestoredState} from '../navigation_transition'; import {ROUTER_CONFIGURATION} from '../router_config'; import {createEmptyState, RouterState} from '../router_state'; import {UrlHandlingStrategy} from '../url_handling_strategy'; import {UrlSerializer, UrlTree} from '../url_tree'; @Injectable({providedIn: 'root', useFactory: () => inject(HistoryStateManager)}) export abstract class StateManager { /** * Returns the currently activated `UrlTree`. * * This `UrlTree` shows only URLs that the `Router` is configured to handle (through * `UrlHandlingStrategy`). * * The value is set after finding the route config tree to activate but before activating the * route. */ abstract getCurrentUrlTree(): UrlTree; /** * Returns a `UrlTree` that is represents what the browser is actually showing. * * In the life of a navigation transition: * 1. When a navigation begins, the raw `UrlTree` is updated to the full URL that's being * navigated to. * 2. During a navigation, redirects are applied, which might only apply to _part_ of the URL (due * to `UrlHandlingStrategy`). * 3. Just before activation, the raw `UrlTree` is updated to include the redirects on top of the * original raw URL. * * Note that this is _only_ here to support `UrlHandlingStrategy.extract` and * `UrlHandlingStrategy.shouldProcessUrl`. Without those APIs, the current `UrlTree` would not * deviated from the raw `UrlTree`. * * For `extract`, a raw `UrlTree` is needed because `extract` may only return part * of the navigation URL. Thus, the current `UrlTree` may only represent _part_ of the browser * URL. When a navigation gets cancelled and the router needs to reset the URL or a new navigation * occurs, it needs to know the _whole_ browser URL, not just the part handled by * `UrlHandlingStrategy`. * For `shouldProcessUrl`, when the return is `false`, the router ignores the navigation but * still updates the raw `UrlTree` with the assumption that the navigation was caused by the * location change listener due to a URL update by the AngularJS router. In this case, the router * still need to know what the browser's URL is for future navigations. */ abstract getRawUrlTree(): UrlTree; /** Returns the current state stored by the browser for the current history entry. */ abstract restoredState(): RestoredState | null | undefined; /** Returns the current RouterState. */ abstract getRouterState(): RouterState; /** * Registers a listener that is called whenever the current history entry changes by some API * outside the Router. This includes user-activated changes like back buttons and link clicks, but * also includes programmatic APIs called by non-Router JavaScript. */ abstract registerNonRouterCurrentEntryChangeListener( listener: (url: string, state: RestoredState | null | undefined) => void, ): SubscriptionLike; /** * Handles a navigation event sent from the Router. These are typically events that indicate a * navigation has started, progressed, been cancelled, or finished. */ abstract handleRouterEvent(e: Event | PrivateRouterEvents, currentTransition: Navigation): void; }
{ "end_byte": 3807, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/router/src/statemanager/state_manager.ts" }