router.js 226 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793
  1. /**
  2. * @license Angular v8.1.0
  3. * (c) 2010-2019 Google LLC. https://angular.io/
  4. * License: MIT
  5. */
  6. import { __extends, __decorate, __assign, __values, __spread, __metadata, __param } from 'tslib';
  7. import { LocationStrategy, Location, PlatformLocation, APP_BASE_HREF, ViewportScroller, HashLocationStrategy, PathLocationStrategy, LOCATION_INITIALIZED } from '@angular/common';
  8. import { Component, ɵisObservable, ɵisPromise, NgModuleRef, InjectionToken, NgModuleFactory, isDevMode, NgZone, ɵConsole, Input, HostListener, Directive, Attribute, Renderer2, ElementRef, HostBinding, ContentChildren, QueryList, Optional, Output, ViewContainerRef, ComponentFactoryResolver, ChangeDetectorRef, EventEmitter, Injectable, NgModuleFactoryLoader, Compiler, Injector, ApplicationRef, SystemJsNgModuleLoader, NgProbeToken, ANALYZE_FOR_ENTRY_COMPONENTS, SkipSelf, Inject, APP_INITIALIZER, APP_BOOTSTRAP_LISTENER, NgModule, Version } from '@angular/core';
  9. import { from, of, BehaviorSubject, EmptyError, Observable, combineLatest, defer, EMPTY, Subject } from 'rxjs';
  10. import { map, concatAll, last as last$1, catchError, first, mergeMap, every, switchMap, take, startWith, scan, filter, concatMap, reduce, tap, finalize, mergeAll } from 'rxjs/operators';
  11. import { ɵgetDOM } from '@angular/platform-browser';
  12. /**
  13. * @license
  14. * Copyright Google Inc. All Rights Reserved.
  15. *
  16. * Use of this source code is governed by an MIT-style license that can be
  17. * found in the LICENSE file at https://angular.io/license
  18. */
  19. /**
  20. * @description
  21. *
  22. * Base for events the Router goes through, as opposed to events tied to a specific
  23. * Route. `RouterEvent`s will only be fired one time for any given navigation.
  24. *
  25. * Example:
  26. *
  27. * ```
  28. * class MyService {
  29. * constructor(public router: Router, logger: Logger) {
  30. * router.events.pipe(
  31. * filter(e => e instanceof RouterEvent)
  32. * ).subscribe(e => {
  33. * logger.log(e.id, e.url);
  34. * });
  35. * }
  36. * }
  37. * ```
  38. *
  39. * @publicApi
  40. */
  41. var RouterEvent = /** @class */ (function () {
  42. function RouterEvent(
  43. /** @docsNotRequired */
  44. id,
  45. /** @docsNotRequired */
  46. url) {
  47. this.id = id;
  48. this.url = url;
  49. }
  50. return RouterEvent;
  51. }());
  52. /**
  53. * @description
  54. *
  55. * Represents an event triggered when a navigation starts.
  56. *
  57. * @publicApi
  58. */
  59. var NavigationStart = /** @class */ (function (_super) {
  60. __extends(NavigationStart, _super);
  61. function NavigationStart(
  62. /** @docsNotRequired */
  63. id,
  64. /** @docsNotRequired */
  65. url,
  66. /** @docsNotRequired */
  67. navigationTrigger,
  68. /** @docsNotRequired */
  69. restoredState) {
  70. if (navigationTrigger === void 0) { navigationTrigger = 'imperative'; }
  71. if (restoredState === void 0) { restoredState = null; }
  72. var _this = _super.call(this, id, url) || this;
  73. _this.navigationTrigger = navigationTrigger;
  74. _this.restoredState = restoredState;
  75. return _this;
  76. }
  77. /** @docsNotRequired */
  78. NavigationStart.prototype.toString = function () { return "NavigationStart(id: " + this.id + ", url: '" + this.url + "')"; };
  79. return NavigationStart;
  80. }(RouterEvent));
  81. /**
  82. * @description
  83. *
  84. * Represents an event triggered when a navigation ends successfully.
  85. *
  86. * @publicApi
  87. */
  88. var NavigationEnd = /** @class */ (function (_super) {
  89. __extends(NavigationEnd, _super);
  90. function NavigationEnd(
  91. /** @docsNotRequired */
  92. id,
  93. /** @docsNotRequired */
  94. url,
  95. /** @docsNotRequired */
  96. urlAfterRedirects) {
  97. var _this = _super.call(this, id, url) || this;
  98. _this.urlAfterRedirects = urlAfterRedirects;
  99. return _this;
  100. }
  101. /** @docsNotRequired */
  102. NavigationEnd.prototype.toString = function () {
  103. return "NavigationEnd(id: " + this.id + ", url: '" + this.url + "', urlAfterRedirects: '" + this.urlAfterRedirects + "')";
  104. };
  105. return NavigationEnd;
  106. }(RouterEvent));
  107. /**
  108. * @description
  109. *
  110. * Represents an event triggered when a navigation is canceled.
  111. *
  112. * @publicApi
  113. */
  114. var NavigationCancel = /** @class */ (function (_super) {
  115. __extends(NavigationCancel, _super);
  116. function NavigationCancel(
  117. /** @docsNotRequired */
  118. id,
  119. /** @docsNotRequired */
  120. url,
  121. /** @docsNotRequired */
  122. reason) {
  123. var _this = _super.call(this, id, url) || this;
  124. _this.reason = reason;
  125. return _this;
  126. }
  127. /** @docsNotRequired */
  128. NavigationCancel.prototype.toString = function () { return "NavigationCancel(id: " + this.id + ", url: '" + this.url + "')"; };
  129. return NavigationCancel;
  130. }(RouterEvent));
  131. /**
  132. * @description
  133. *
  134. * Represents an event triggered when a navigation fails due to an unexpected error.
  135. *
  136. * @publicApi
  137. */
  138. var NavigationError = /** @class */ (function (_super) {
  139. __extends(NavigationError, _super);
  140. function NavigationError(
  141. /** @docsNotRequired */
  142. id,
  143. /** @docsNotRequired */
  144. url,
  145. /** @docsNotRequired */
  146. error) {
  147. var _this = _super.call(this, id, url) || this;
  148. _this.error = error;
  149. return _this;
  150. }
  151. /** @docsNotRequired */
  152. NavigationError.prototype.toString = function () {
  153. return "NavigationError(id: " + this.id + ", url: '" + this.url + "', error: " + this.error + ")";
  154. };
  155. return NavigationError;
  156. }(RouterEvent));
  157. /**
  158. * @description
  159. *
  160. * Represents an event triggered when routes are recognized.
  161. *
  162. * @publicApi
  163. */
  164. var RoutesRecognized = /** @class */ (function (_super) {
  165. __extends(RoutesRecognized, _super);
  166. function RoutesRecognized(
  167. /** @docsNotRequired */
  168. id,
  169. /** @docsNotRequired */
  170. url,
  171. /** @docsNotRequired */
  172. urlAfterRedirects,
  173. /** @docsNotRequired */
  174. state) {
  175. var _this = _super.call(this, id, url) || this;
  176. _this.urlAfterRedirects = urlAfterRedirects;
  177. _this.state = state;
  178. return _this;
  179. }
  180. /** @docsNotRequired */
  181. RoutesRecognized.prototype.toString = function () {
  182. return "RoutesRecognized(id: " + this.id + ", url: '" + this.url + "', urlAfterRedirects: '" + this.urlAfterRedirects + "', state: " + this.state + ")";
  183. };
  184. return RoutesRecognized;
  185. }(RouterEvent));
  186. /**
  187. * @description
  188. *
  189. * Represents the start of the Guard phase of routing.
  190. *
  191. * @publicApi
  192. */
  193. var GuardsCheckStart = /** @class */ (function (_super) {
  194. __extends(GuardsCheckStart, _super);
  195. function GuardsCheckStart(
  196. /** @docsNotRequired */
  197. id,
  198. /** @docsNotRequired */
  199. url,
  200. /** @docsNotRequired */
  201. urlAfterRedirects,
  202. /** @docsNotRequired */
  203. state) {
  204. var _this = _super.call(this, id, url) || this;
  205. _this.urlAfterRedirects = urlAfterRedirects;
  206. _this.state = state;
  207. return _this;
  208. }
  209. GuardsCheckStart.prototype.toString = function () {
  210. return "GuardsCheckStart(id: " + this.id + ", url: '" + this.url + "', urlAfterRedirects: '" + this.urlAfterRedirects + "', state: " + this.state + ")";
  211. };
  212. return GuardsCheckStart;
  213. }(RouterEvent));
  214. /**
  215. * @description
  216. *
  217. * Represents the end of the Guard phase of routing.
  218. *
  219. * @publicApi
  220. */
  221. var GuardsCheckEnd = /** @class */ (function (_super) {
  222. __extends(GuardsCheckEnd, _super);
  223. function GuardsCheckEnd(
  224. /** @docsNotRequired */
  225. id,
  226. /** @docsNotRequired */
  227. url,
  228. /** @docsNotRequired */
  229. urlAfterRedirects,
  230. /** @docsNotRequired */
  231. state,
  232. /** @docsNotRequired */
  233. shouldActivate) {
  234. var _this = _super.call(this, id, url) || this;
  235. _this.urlAfterRedirects = urlAfterRedirects;
  236. _this.state = state;
  237. _this.shouldActivate = shouldActivate;
  238. return _this;
  239. }
  240. GuardsCheckEnd.prototype.toString = function () {
  241. return "GuardsCheckEnd(id: " + this.id + ", url: '" + this.url + "', urlAfterRedirects: '" + this.urlAfterRedirects + "', state: " + this.state + ", shouldActivate: " + this.shouldActivate + ")";
  242. };
  243. return GuardsCheckEnd;
  244. }(RouterEvent));
  245. /**
  246. * @description
  247. *
  248. * Represents the start of the Resolve phase of routing. The timing of this
  249. * event may change, thus it's experimental. In the current iteration it will run
  250. * in the "resolve" phase whether there's things to resolve or not. In the future this
  251. * behavior may change to only run when there are things to be resolved.
  252. *
  253. * @publicApi
  254. */
  255. var ResolveStart = /** @class */ (function (_super) {
  256. __extends(ResolveStart, _super);
  257. function ResolveStart(
  258. /** @docsNotRequired */
  259. id,
  260. /** @docsNotRequired */
  261. url,
  262. /** @docsNotRequired */
  263. urlAfterRedirects,
  264. /** @docsNotRequired */
  265. state) {
  266. var _this = _super.call(this, id, url) || this;
  267. _this.urlAfterRedirects = urlAfterRedirects;
  268. _this.state = state;
  269. return _this;
  270. }
  271. ResolveStart.prototype.toString = function () {
  272. return "ResolveStart(id: " + this.id + ", url: '" + this.url + "', urlAfterRedirects: '" + this.urlAfterRedirects + "', state: " + this.state + ")";
  273. };
  274. return ResolveStart;
  275. }(RouterEvent));
  276. /**
  277. * @description
  278. *
  279. * Represents the end of the Resolve phase of routing. See note on
  280. * `ResolveStart` for use of this experimental API.
  281. *
  282. * @publicApi
  283. */
  284. var ResolveEnd = /** @class */ (function (_super) {
  285. __extends(ResolveEnd, _super);
  286. function ResolveEnd(
  287. /** @docsNotRequired */
  288. id,
  289. /** @docsNotRequired */
  290. url,
  291. /** @docsNotRequired */
  292. urlAfterRedirects,
  293. /** @docsNotRequired */
  294. state) {
  295. var _this = _super.call(this, id, url) || this;
  296. _this.urlAfterRedirects = urlAfterRedirects;
  297. _this.state = state;
  298. return _this;
  299. }
  300. ResolveEnd.prototype.toString = function () {
  301. return "ResolveEnd(id: " + this.id + ", url: '" + this.url + "', urlAfterRedirects: '" + this.urlAfterRedirects + "', state: " + this.state + ")";
  302. };
  303. return ResolveEnd;
  304. }(RouterEvent));
  305. /**
  306. * @description
  307. *
  308. * Represents an event triggered before lazy loading a route config.
  309. *
  310. * @publicApi
  311. */
  312. var RouteConfigLoadStart = /** @class */ (function () {
  313. function RouteConfigLoadStart(
  314. /** @docsNotRequired */
  315. route) {
  316. this.route = route;
  317. }
  318. RouteConfigLoadStart.prototype.toString = function () { return "RouteConfigLoadStart(path: " + this.route.path + ")"; };
  319. return RouteConfigLoadStart;
  320. }());
  321. /**
  322. * @description
  323. *
  324. * Represents an event triggered when a route has been lazy loaded.
  325. *
  326. * @publicApi
  327. */
  328. var RouteConfigLoadEnd = /** @class */ (function () {
  329. function RouteConfigLoadEnd(
  330. /** @docsNotRequired */
  331. route) {
  332. this.route = route;
  333. }
  334. RouteConfigLoadEnd.prototype.toString = function () { return "RouteConfigLoadEnd(path: " + this.route.path + ")"; };
  335. return RouteConfigLoadEnd;
  336. }());
  337. /**
  338. * @description
  339. *
  340. * Represents the start of end of the Resolve phase of routing. See note on
  341. * `ChildActivationEnd` for use of this experimental API.
  342. *
  343. * @publicApi
  344. */
  345. var ChildActivationStart = /** @class */ (function () {
  346. function ChildActivationStart(
  347. /** @docsNotRequired */
  348. snapshot) {
  349. this.snapshot = snapshot;
  350. }
  351. ChildActivationStart.prototype.toString = function () {
  352. var path = this.snapshot.routeConfig && this.snapshot.routeConfig.path || '';
  353. return "ChildActivationStart(path: '" + path + "')";
  354. };
  355. return ChildActivationStart;
  356. }());
  357. /**
  358. * @description
  359. *
  360. * Represents the start of end of the Resolve phase of routing. See note on
  361. * `ChildActivationStart` for use of this experimental API.
  362. *
  363. * @publicApi
  364. */
  365. var ChildActivationEnd = /** @class */ (function () {
  366. function ChildActivationEnd(
  367. /** @docsNotRequired */
  368. snapshot) {
  369. this.snapshot = snapshot;
  370. }
  371. ChildActivationEnd.prototype.toString = function () {
  372. var path = this.snapshot.routeConfig && this.snapshot.routeConfig.path || '';
  373. return "ChildActivationEnd(path: '" + path + "')";
  374. };
  375. return ChildActivationEnd;
  376. }());
  377. /**
  378. * @description
  379. *
  380. * Represents the start of end of the Resolve phase of routing. See note on
  381. * `ActivationEnd` for use of this experimental API.
  382. *
  383. * @publicApi
  384. */
  385. var ActivationStart = /** @class */ (function () {
  386. function ActivationStart(
  387. /** @docsNotRequired */
  388. snapshot) {
  389. this.snapshot = snapshot;
  390. }
  391. ActivationStart.prototype.toString = function () {
  392. var path = this.snapshot.routeConfig && this.snapshot.routeConfig.path || '';
  393. return "ActivationStart(path: '" + path + "')";
  394. };
  395. return ActivationStart;
  396. }());
  397. /**
  398. * @description
  399. *
  400. * Represents the start of end of the Resolve phase of routing. See note on
  401. * `ActivationStart` for use of this experimental API.
  402. *
  403. * @publicApi
  404. */
  405. var ActivationEnd = /** @class */ (function () {
  406. function ActivationEnd(
  407. /** @docsNotRequired */
  408. snapshot) {
  409. this.snapshot = snapshot;
  410. }
  411. ActivationEnd.prototype.toString = function () {
  412. var path = this.snapshot.routeConfig && this.snapshot.routeConfig.path || '';
  413. return "ActivationEnd(path: '" + path + "')";
  414. };
  415. return ActivationEnd;
  416. }());
  417. /**
  418. * @description
  419. *
  420. * Represents a scrolling event.
  421. *
  422. * @publicApi
  423. */
  424. var Scroll = /** @class */ (function () {
  425. function Scroll(
  426. /** @docsNotRequired */
  427. routerEvent,
  428. /** @docsNotRequired */
  429. position,
  430. /** @docsNotRequired */
  431. anchor) {
  432. this.routerEvent = routerEvent;
  433. this.position = position;
  434. this.anchor = anchor;
  435. }
  436. Scroll.prototype.toString = function () {
  437. var pos = this.position ? this.position[0] + ", " + this.position[1] : null;
  438. return "Scroll(anchor: '" + this.anchor + "', position: '" + pos + "')";
  439. };
  440. return Scroll;
  441. }());
  442. /**
  443. * @license
  444. * Copyright Google Inc. All Rights Reserved.
  445. *
  446. * Use of this source code is governed by an MIT-style license that can be
  447. * found in the LICENSE file at https://angular.io/license
  448. */
  449. /**
  450. * This component is used internally within the router to be a placeholder when an empty
  451. * router-outlet is needed. For example, with a config such as:
  452. *
  453. * `{path: 'parent', outlet: 'nav', children: [...]}`
  454. *
  455. * In order to render, there needs to be a component on this config, which will default
  456. * to this `EmptyOutletComponent`.
  457. */
  458. var ɵEmptyOutletComponent = /** @class */ (function () {
  459. function ɵEmptyOutletComponent() {
  460. }
  461. ɵEmptyOutletComponent = __decorate([
  462. Component({ template: "<router-outlet></router-outlet>" })
  463. ], ɵEmptyOutletComponent);
  464. return ɵEmptyOutletComponent;
  465. }());
  466. /**
  467. * @license
  468. * Copyright Google Inc. All Rights Reserved.
  469. *
  470. * Use of this source code is governed by an MIT-style license that can be
  471. * found in the LICENSE file at https://angular.io/license
  472. */
  473. /**
  474. * @description
  475. *
  476. * Name of the primary outlet.
  477. *
  478. * @publicApi
  479. */
  480. var PRIMARY_OUTLET = 'primary';
  481. var ParamsAsMap = /** @class */ (function () {
  482. function ParamsAsMap(params) {
  483. this.params = params || {};
  484. }
  485. ParamsAsMap.prototype.has = function (name) { return this.params.hasOwnProperty(name); };
  486. ParamsAsMap.prototype.get = function (name) {
  487. if (this.has(name)) {
  488. var v = this.params[name];
  489. return Array.isArray(v) ? v[0] : v;
  490. }
  491. return null;
  492. };
  493. ParamsAsMap.prototype.getAll = function (name) {
  494. if (this.has(name)) {
  495. var v = this.params[name];
  496. return Array.isArray(v) ? v : [v];
  497. }
  498. return [];
  499. };
  500. Object.defineProperty(ParamsAsMap.prototype, "keys", {
  501. get: function () { return Object.keys(this.params); },
  502. enumerable: true,
  503. configurable: true
  504. });
  505. return ParamsAsMap;
  506. }());
  507. /**
  508. * Convert a `Params` instance to a `ParamMap`.
  509. *
  510. * @publicApi
  511. */
  512. function convertToParamMap(params) {
  513. return new ParamsAsMap(params);
  514. }
  515. var NAVIGATION_CANCELING_ERROR = 'ngNavigationCancelingError';
  516. function navigationCancelingError(message) {
  517. var error = Error('NavigationCancelingError: ' + message);
  518. error[NAVIGATION_CANCELING_ERROR] = true;
  519. return error;
  520. }
  521. function isNavigationCancelingError(error) {
  522. return error && error[NAVIGATION_CANCELING_ERROR];
  523. }
  524. // Matches the route configuration (`route`) against the actual URL (`segments`).
  525. function defaultUrlMatcher(segments, segmentGroup, route) {
  526. var parts = route.path.split('/');
  527. if (parts.length > segments.length) {
  528. // The actual URL is shorter than the config, no match
  529. return null;
  530. }
  531. if (route.pathMatch === 'full' &&
  532. (segmentGroup.hasChildren() || parts.length < segments.length)) {
  533. // The config is longer than the actual URL but we are looking for a full match, return null
  534. return null;
  535. }
  536. var posParams = {};
  537. // Check each config part against the actual URL
  538. for (var index = 0; index < parts.length; index++) {
  539. var part = parts[index];
  540. var segment = segments[index];
  541. var isParameter = part.startsWith(':');
  542. if (isParameter) {
  543. posParams[part.substring(1)] = segment;
  544. }
  545. else if (part !== segment.path) {
  546. // The actual URL part does not match the config, no match
  547. return null;
  548. }
  549. }
  550. return { consumed: segments.slice(0, parts.length), posParams: posParams };
  551. }
  552. /**
  553. * @license
  554. * Copyright Google Inc. All Rights Reserved.
  555. *
  556. * Use of this source code is governed by an MIT-style license that can be
  557. * found in the LICENSE file at https://angular.io/license
  558. */
  559. var LoadedRouterConfig = /** @class */ (function () {
  560. function LoadedRouterConfig(routes, module) {
  561. this.routes = routes;
  562. this.module = module;
  563. }
  564. return LoadedRouterConfig;
  565. }());
  566. function validateConfig(config, parentPath) {
  567. if (parentPath === void 0) { parentPath = ''; }
  568. // forEach doesn't iterate undefined values
  569. for (var i = 0; i < config.length; i++) {
  570. var route = config[i];
  571. var fullPath = getFullPath(parentPath, route);
  572. validateNode(route, fullPath);
  573. }
  574. }
  575. function validateNode(route, fullPath) {
  576. if (!route) {
  577. throw new Error("\n Invalid configuration of route '" + fullPath + "': Encountered undefined route.\n The reason might be an extra comma.\n\n Example:\n const routes: Routes = [\n { path: '', redirectTo: '/dashboard', pathMatch: 'full' },\n { path: 'dashboard', component: DashboardComponent },, << two commas\n { path: 'detail/:id', component: HeroDetailComponent }\n ];\n ");
  578. }
  579. if (Array.isArray(route)) {
  580. throw new Error("Invalid configuration of route '" + fullPath + "': Array cannot be specified");
  581. }
  582. if (!route.component && !route.children && !route.loadChildren &&
  583. (route.outlet && route.outlet !== PRIMARY_OUTLET)) {
  584. throw new Error("Invalid configuration of route '" + fullPath + "': a componentless route without children or loadChildren cannot have a named outlet set");
  585. }
  586. if (route.redirectTo && route.children) {
  587. throw new Error("Invalid configuration of route '" + fullPath + "': redirectTo and children cannot be used together");
  588. }
  589. if (route.redirectTo && route.loadChildren) {
  590. throw new Error("Invalid configuration of route '" + fullPath + "': redirectTo and loadChildren cannot be used together");
  591. }
  592. if (route.children && route.loadChildren) {
  593. throw new Error("Invalid configuration of route '" + fullPath + "': children and loadChildren cannot be used together");
  594. }
  595. if (route.redirectTo && route.component) {
  596. throw new Error("Invalid configuration of route '" + fullPath + "': redirectTo and component cannot be used together");
  597. }
  598. if (route.path && route.matcher) {
  599. throw new Error("Invalid configuration of route '" + fullPath + "': path and matcher cannot be used together");
  600. }
  601. if (route.redirectTo === void 0 && !route.component && !route.children && !route.loadChildren) {
  602. throw new Error("Invalid configuration of route '" + fullPath + "'. One of the following must be provided: component, redirectTo, children or loadChildren");
  603. }
  604. if (route.path === void 0 && route.matcher === void 0) {
  605. throw new Error("Invalid configuration of route '" + fullPath + "': routes must have either a path or a matcher specified");
  606. }
  607. if (typeof route.path === 'string' && route.path.charAt(0) === '/') {
  608. throw new Error("Invalid configuration of route '" + fullPath + "': path cannot start with a slash");
  609. }
  610. if (route.path === '' && route.redirectTo !== void 0 && route.pathMatch === void 0) {
  611. var exp = "The default value of 'pathMatch' is 'prefix', but often the intent is to use 'full'.";
  612. throw new Error("Invalid configuration of route '{path: \"" + fullPath + "\", redirectTo: \"" + route.redirectTo + "\"}': please provide 'pathMatch'. " + exp);
  613. }
  614. if (route.pathMatch !== void 0 && route.pathMatch !== 'full' && route.pathMatch !== 'prefix') {
  615. throw new Error("Invalid configuration of route '" + fullPath + "': pathMatch can only be set to 'prefix' or 'full'");
  616. }
  617. if (route.children) {
  618. validateConfig(route.children, fullPath);
  619. }
  620. }
  621. function getFullPath(parentPath, currentRoute) {
  622. if (!currentRoute) {
  623. return parentPath;
  624. }
  625. if (!parentPath && !currentRoute.path) {
  626. return '';
  627. }
  628. else if (parentPath && !currentRoute.path) {
  629. return parentPath + "/";
  630. }
  631. else if (!parentPath && currentRoute.path) {
  632. return currentRoute.path;
  633. }
  634. else {
  635. return parentPath + "/" + currentRoute.path;
  636. }
  637. }
  638. /**
  639. * Makes a copy of the config and adds any default required properties.
  640. */
  641. function standardizeConfig(r) {
  642. var children = r.children && r.children.map(standardizeConfig);
  643. var c = children ? __assign({}, r, { children: children }) : __assign({}, r);
  644. if (!c.component && (children || c.loadChildren) && (c.outlet && c.outlet !== PRIMARY_OUTLET)) {
  645. c.component = ɵEmptyOutletComponent;
  646. }
  647. return c;
  648. }
  649. /**
  650. * @license
  651. * Copyright Google Inc. All Rights Reserved.
  652. *
  653. * Use of this source code is governed by an MIT-style license that can be
  654. * found in the LICENSE file at https://angular.io/license
  655. */
  656. function shallowEqualArrays(a, b) {
  657. if (a.length !== b.length)
  658. return false;
  659. for (var i = 0; i < a.length; ++i) {
  660. if (!shallowEqual(a[i], b[i]))
  661. return false;
  662. }
  663. return true;
  664. }
  665. function shallowEqual(a, b) {
  666. // Casting Object.keys return values to include `undefined` as there are some cases
  667. // in IE 11 where this can happen. Cannot provide a test because the behavior only
  668. // exists in certain circumstances in IE 11, therefore doing this cast ensures the
  669. // logic is correct for when this edge case is hit.
  670. var k1 = Object.keys(a);
  671. var k2 = Object.keys(b);
  672. if (!k1 || !k2 || k1.length != k2.length) {
  673. return false;
  674. }
  675. var key;
  676. for (var i = 0; i < k1.length; i++) {
  677. key = k1[i];
  678. if (a[key] !== b[key]) {
  679. return false;
  680. }
  681. }
  682. return true;
  683. }
  684. /**
  685. * Flattens single-level nested arrays.
  686. */
  687. function flatten(arr) {
  688. return Array.prototype.concat.apply([], arr);
  689. }
  690. /**
  691. * Return the last element of an array.
  692. */
  693. function last(a) {
  694. return a.length > 0 ? a[a.length - 1] : null;
  695. }
  696. function forEach(map, callback) {
  697. for (var prop in map) {
  698. if (map.hasOwnProperty(prop)) {
  699. callback(map[prop], prop);
  700. }
  701. }
  702. }
  703. function waitForMap(obj, fn) {
  704. if (Object.keys(obj).length === 0) {
  705. return of({});
  706. }
  707. var waitHead = [];
  708. var waitTail = [];
  709. var res = {};
  710. forEach(obj, function (a, k) {
  711. var mapped = fn(k, a).pipe(map(function (r) { return res[k] = r; }));
  712. if (k === PRIMARY_OUTLET) {
  713. waitHead.push(mapped);
  714. }
  715. else {
  716. waitTail.push(mapped);
  717. }
  718. });
  719. // Closure compiler has problem with using spread operator here. So just using Array.concat.
  720. return of.apply(null, waitHead.concat(waitTail)).pipe(concatAll(), last$1(), map(function () { return res; }));
  721. }
  722. function wrapIntoObservable(value) {
  723. if (ɵisObservable(value)) {
  724. return value;
  725. }
  726. if (ɵisPromise(value)) {
  727. // Use `Promise.resolve()` to wrap promise-like instances.
  728. // Required ie when a Resolver returns a AngularJS `$q` promise to correctly trigger the
  729. // change detection.
  730. return from(Promise.resolve(value));
  731. }
  732. return of(value);
  733. }
  734. /**
  735. * @license
  736. * Copyright Google Inc. All Rights Reserved.
  737. *
  738. * Use of this source code is governed by an MIT-style license that can be
  739. * found in the LICENSE file at https://angular.io/license
  740. */
  741. function createEmptyUrlTree() {
  742. return new UrlTree(new UrlSegmentGroup([], {}), {}, null);
  743. }
  744. function containsTree(container, containee, exact) {
  745. if (exact) {
  746. return equalQueryParams(container.queryParams, containee.queryParams) &&
  747. equalSegmentGroups(container.root, containee.root);
  748. }
  749. return containsQueryParams(container.queryParams, containee.queryParams) &&
  750. containsSegmentGroup(container.root, containee.root);
  751. }
  752. function equalQueryParams(container, containee) {
  753. // TODO: This does not handle array params correctly.
  754. return shallowEqual(container, containee);
  755. }
  756. function equalSegmentGroups(container, containee) {
  757. if (!equalPath(container.segments, containee.segments))
  758. return false;
  759. if (container.numberOfChildren !== containee.numberOfChildren)
  760. return false;
  761. for (var c in containee.children) {
  762. if (!container.children[c])
  763. return false;
  764. if (!equalSegmentGroups(container.children[c], containee.children[c]))
  765. return false;
  766. }
  767. return true;
  768. }
  769. function containsQueryParams(container, containee) {
  770. // TODO: This does not handle array params correctly.
  771. return Object.keys(containee).length <= Object.keys(container).length &&
  772. Object.keys(containee).every(function (key) { return containee[key] === container[key]; });
  773. }
  774. function containsSegmentGroup(container, containee) {
  775. return containsSegmentGroupHelper(container, containee, containee.segments);
  776. }
  777. function containsSegmentGroupHelper(container, containee, containeePaths) {
  778. if (container.segments.length > containeePaths.length) {
  779. var current = container.segments.slice(0, containeePaths.length);
  780. if (!equalPath(current, containeePaths))
  781. return false;
  782. if (containee.hasChildren())
  783. return false;
  784. return true;
  785. }
  786. else if (container.segments.length === containeePaths.length) {
  787. if (!equalPath(container.segments, containeePaths))
  788. return false;
  789. for (var c in containee.children) {
  790. if (!container.children[c])
  791. return false;
  792. if (!containsSegmentGroup(container.children[c], containee.children[c]))
  793. return false;
  794. }
  795. return true;
  796. }
  797. else {
  798. var current = containeePaths.slice(0, container.segments.length);
  799. var next = containeePaths.slice(container.segments.length);
  800. if (!equalPath(container.segments, current))
  801. return false;
  802. if (!container.children[PRIMARY_OUTLET])
  803. return false;
  804. return containsSegmentGroupHelper(container.children[PRIMARY_OUTLET], containee, next);
  805. }
  806. }
  807. /**
  808. * @description
  809. *
  810. * Represents the parsed URL.
  811. *
  812. * Since a router state is a tree, and the URL is nothing but a serialized state, the URL is a
  813. * serialized tree.
  814. * UrlTree is a data structure that provides a lot of affordances in dealing with URLs
  815. *
  816. * @usageNotes
  817. * ### Example
  818. *
  819. * ```
  820. * @Component({templateUrl:'template.html'})
  821. * class MyComponent {
  822. * constructor(router: Router) {
  823. * const tree: UrlTree =
  824. * router.parseUrl('/team/33/(user/victor//support:help)?debug=true#fragment');
  825. * const f = tree.fragment; // return 'fragment'
  826. * const q = tree.queryParams; // returns {debug: 'true'}
  827. * const g: UrlSegmentGroup = tree.root.children[PRIMARY_OUTLET];
  828. * const s: UrlSegment[] = g.segments; // returns 2 segments 'team' and '33'
  829. * g.children[PRIMARY_OUTLET].segments; // returns 2 segments 'user' and 'victor'
  830. * g.children['support'].segments; // return 1 segment 'help'
  831. * }
  832. * }
  833. * ```
  834. *
  835. * @publicApi
  836. */
  837. var UrlTree = /** @class */ (function () {
  838. /** @internal */
  839. function UrlTree(
  840. /** The root segment group of the URL tree */
  841. root,
  842. /** The query params of the URL */
  843. queryParams,
  844. /** The fragment of the URL */
  845. fragment) {
  846. this.root = root;
  847. this.queryParams = queryParams;
  848. this.fragment = fragment;
  849. }
  850. Object.defineProperty(UrlTree.prototype, "queryParamMap", {
  851. get: function () {
  852. if (!this._queryParamMap) {
  853. this._queryParamMap = convertToParamMap(this.queryParams);
  854. }
  855. return this._queryParamMap;
  856. },
  857. enumerable: true,
  858. configurable: true
  859. });
  860. /** @docsNotRequired */
  861. UrlTree.prototype.toString = function () { return DEFAULT_SERIALIZER.serialize(this); };
  862. return UrlTree;
  863. }());
  864. /**
  865. * @description
  866. *
  867. * Represents the parsed URL segment group.
  868. *
  869. * See `UrlTree` for more information.
  870. *
  871. * @publicApi
  872. */
  873. var UrlSegmentGroup = /** @class */ (function () {
  874. function UrlSegmentGroup(
  875. /** The URL segments of this group. See `UrlSegment` for more information */
  876. segments,
  877. /** The list of children of this group */
  878. children) {
  879. var _this = this;
  880. this.segments = segments;
  881. this.children = children;
  882. /** The parent node in the url tree */
  883. this.parent = null;
  884. forEach(children, function (v, k) { return v.parent = _this; });
  885. }
  886. /** Whether the segment has child segments */
  887. UrlSegmentGroup.prototype.hasChildren = function () { return this.numberOfChildren > 0; };
  888. Object.defineProperty(UrlSegmentGroup.prototype, "numberOfChildren", {
  889. /** Number of child segments */
  890. get: function () { return Object.keys(this.children).length; },
  891. enumerable: true,
  892. configurable: true
  893. });
  894. /** @docsNotRequired */
  895. UrlSegmentGroup.prototype.toString = function () { return serializePaths(this); };
  896. return UrlSegmentGroup;
  897. }());
  898. /**
  899. * @description
  900. *
  901. * Represents a single URL segment.
  902. *
  903. * A UrlSegment is a part of a URL between the two slashes. It contains a path and the matrix
  904. * parameters associated with the segment.
  905. *
  906. * @usageNotes
  907. * ### Example
  908. *
  909. * ```
  910. * @Component({templateUrl:'template.html'})
  911. * class MyComponent {
  912. * constructor(router: Router) {
  913. * const tree: UrlTree = router.parseUrl('/team;id=33');
  914. * const g: UrlSegmentGroup = tree.root.children[PRIMARY_OUTLET];
  915. * const s: UrlSegment[] = g.segments;
  916. * s[0].path; // returns 'team'
  917. * s[0].parameters; // returns {id: 33}
  918. * }
  919. * }
  920. * ```
  921. *
  922. * @publicApi
  923. */
  924. var UrlSegment = /** @class */ (function () {
  925. function UrlSegment(
  926. /** The path part of a URL segment */
  927. path,
  928. /** The matrix parameters associated with a segment */
  929. parameters) {
  930. this.path = path;
  931. this.parameters = parameters;
  932. }
  933. Object.defineProperty(UrlSegment.prototype, "parameterMap", {
  934. get: function () {
  935. if (!this._parameterMap) {
  936. this._parameterMap = convertToParamMap(this.parameters);
  937. }
  938. return this._parameterMap;
  939. },
  940. enumerable: true,
  941. configurable: true
  942. });
  943. /** @docsNotRequired */
  944. UrlSegment.prototype.toString = function () { return serializePath(this); };
  945. return UrlSegment;
  946. }());
  947. function equalSegments(as, bs) {
  948. return equalPath(as, bs) && as.every(function (a, i) { return shallowEqual(a.parameters, bs[i].parameters); });
  949. }
  950. function equalPath(as, bs) {
  951. if (as.length !== bs.length)
  952. return false;
  953. return as.every(function (a, i) { return a.path === bs[i].path; });
  954. }
  955. function mapChildrenIntoArray(segment, fn) {
  956. var res = [];
  957. forEach(segment.children, function (child, childOutlet) {
  958. if (childOutlet === PRIMARY_OUTLET) {
  959. res = res.concat(fn(child, childOutlet));
  960. }
  961. });
  962. forEach(segment.children, function (child, childOutlet) {
  963. if (childOutlet !== PRIMARY_OUTLET) {
  964. res = res.concat(fn(child, childOutlet));
  965. }
  966. });
  967. return res;
  968. }
  969. /**
  970. * @description
  971. *
  972. * Serializes and deserializes a URL string into a URL tree.
  973. *
  974. * The url serialization strategy is customizable. You can
  975. * make all URLs case insensitive by providing a custom UrlSerializer.
  976. *
  977. * See `DefaultUrlSerializer` for an example of a URL serializer.
  978. *
  979. * @publicApi
  980. */
  981. var UrlSerializer = /** @class */ (function () {
  982. function UrlSerializer() {
  983. }
  984. return UrlSerializer;
  985. }());
  986. /**
  987. * @description
  988. *
  989. * A default implementation of the `UrlSerializer`.
  990. *
  991. * Example URLs:
  992. *
  993. * ```
  994. * /inbox/33(popup:compose)
  995. * /inbox/33;open=true/messages/44
  996. * ```
  997. *
  998. * DefaultUrlSerializer uses parentheses to serialize secondary segments (e.g., popup:compose), the
  999. * colon syntax to specify the outlet, and the ';parameter=value' syntax (e.g., open=true) to
  1000. * specify route specific parameters.
  1001. *
  1002. * @publicApi
  1003. */
  1004. var DefaultUrlSerializer = /** @class */ (function () {
  1005. function DefaultUrlSerializer() {
  1006. }
  1007. /** Parses a url into a `UrlTree` */
  1008. DefaultUrlSerializer.prototype.parse = function (url) {
  1009. var p = new UrlParser(url);
  1010. return new UrlTree(p.parseRootSegment(), p.parseQueryParams(), p.parseFragment());
  1011. };
  1012. /** Converts a `UrlTree` into a url */
  1013. DefaultUrlSerializer.prototype.serialize = function (tree) {
  1014. var segment = "/" + serializeSegment(tree.root, true);
  1015. var query = serializeQueryParams(tree.queryParams);
  1016. var fragment = typeof tree.fragment === "string" ? "#" + encodeUriFragment(tree.fragment) : '';
  1017. return "" + segment + query + fragment;
  1018. };
  1019. return DefaultUrlSerializer;
  1020. }());
  1021. var DEFAULT_SERIALIZER = new DefaultUrlSerializer();
  1022. function serializePaths(segment) {
  1023. return segment.segments.map(function (p) { return serializePath(p); }).join('/');
  1024. }
  1025. function serializeSegment(segment, root) {
  1026. if (!segment.hasChildren()) {
  1027. return serializePaths(segment);
  1028. }
  1029. if (root) {
  1030. var primary = segment.children[PRIMARY_OUTLET] ?
  1031. serializeSegment(segment.children[PRIMARY_OUTLET], false) :
  1032. '';
  1033. var children_1 = [];
  1034. forEach(segment.children, function (v, k) {
  1035. if (k !== PRIMARY_OUTLET) {
  1036. children_1.push(k + ":" + serializeSegment(v, false));
  1037. }
  1038. });
  1039. return children_1.length > 0 ? primary + "(" + children_1.join('//') + ")" : primary;
  1040. }
  1041. else {
  1042. var children = mapChildrenIntoArray(segment, function (v, k) {
  1043. if (k === PRIMARY_OUTLET) {
  1044. return [serializeSegment(segment.children[PRIMARY_OUTLET], false)];
  1045. }
  1046. return [k + ":" + serializeSegment(v, false)];
  1047. });
  1048. return serializePaths(segment) + "/(" + children.join('//') + ")";
  1049. }
  1050. }
  1051. /**
  1052. * Encodes a URI string with the default encoding. This function will only ever be called from
  1053. * `encodeUriQuery` or `encodeUriSegment` as it's the base set of encodings to be used. We need
  1054. * a custom encoding because encodeURIComponent is too aggressive and encodes stuff that doesn't
  1055. * have to be encoded per https://url.spec.whatwg.org.
  1056. */
  1057. function encodeUriString(s) {
  1058. return encodeURIComponent(s)
  1059. .replace(/%40/g, '@')
  1060. .replace(/%3A/gi, ':')
  1061. .replace(/%24/g, '$')
  1062. .replace(/%2C/gi, ',');
  1063. }
  1064. /**
  1065. * This function should be used to encode both keys and values in a query string key/value. In
  1066. * the following URL, you need to call encodeUriQuery on "k" and "v":
  1067. *
  1068. * http://www.site.org/html;mk=mv?k=v#f
  1069. */
  1070. function encodeUriQuery(s) {
  1071. return encodeUriString(s).replace(/%3B/gi, ';');
  1072. }
  1073. /**
  1074. * This function should be used to encode a URL fragment. In the following URL, you need to call
  1075. * encodeUriFragment on "f":
  1076. *
  1077. * http://www.site.org/html;mk=mv?k=v#f
  1078. */
  1079. function encodeUriFragment(s) {
  1080. return encodeURI(s);
  1081. }
  1082. /**
  1083. * This function should be run on any URI segment as well as the key and value in a key/value
  1084. * pair for matrix params. In the following URL, you need to call encodeUriSegment on "html",
  1085. * "mk", and "mv":
  1086. *
  1087. * http://www.site.org/html;mk=mv?k=v#f
  1088. */
  1089. function encodeUriSegment(s) {
  1090. return encodeUriString(s).replace(/\(/g, '%28').replace(/\)/g, '%29').replace(/%26/gi, '&');
  1091. }
  1092. function decode(s) {
  1093. return decodeURIComponent(s);
  1094. }
  1095. // Query keys/values should have the "+" replaced first, as "+" in a query string is " ".
  1096. // decodeURIComponent function will not decode "+" as a space.
  1097. function decodeQuery(s) {
  1098. return decode(s.replace(/\+/g, '%20'));
  1099. }
  1100. function serializePath(path) {
  1101. return "" + encodeUriSegment(path.path) + serializeMatrixParams(path.parameters);
  1102. }
  1103. function serializeMatrixParams(params) {
  1104. return Object.keys(params)
  1105. .map(function (key) { return ";" + encodeUriSegment(key) + "=" + encodeUriSegment(params[key]); })
  1106. .join('');
  1107. }
  1108. function serializeQueryParams(params) {
  1109. var strParams = Object.keys(params).map(function (name) {
  1110. var value = params[name];
  1111. return Array.isArray(value) ?
  1112. value.map(function (v) { return encodeUriQuery(name) + "=" + encodeUriQuery(v); }).join('&') :
  1113. encodeUriQuery(name) + "=" + encodeUriQuery(value);
  1114. });
  1115. return strParams.length ? "?" + strParams.join("&") : '';
  1116. }
  1117. var SEGMENT_RE = /^[^\/()?;=#]+/;
  1118. function matchSegments(str) {
  1119. var match = str.match(SEGMENT_RE);
  1120. return match ? match[0] : '';
  1121. }
  1122. var QUERY_PARAM_RE = /^[^=?&#]+/;
  1123. // Return the name of the query param at the start of the string or an empty string
  1124. function matchQueryParams(str) {
  1125. var match = str.match(QUERY_PARAM_RE);
  1126. return match ? match[0] : '';
  1127. }
  1128. var QUERY_PARAM_VALUE_RE = /^[^?&#]+/;
  1129. // Return the value of the query param at the start of the string or an empty string
  1130. function matchUrlQueryParamValue(str) {
  1131. var match = str.match(QUERY_PARAM_VALUE_RE);
  1132. return match ? match[0] : '';
  1133. }
  1134. var UrlParser = /** @class */ (function () {
  1135. function UrlParser(url) {
  1136. this.url = url;
  1137. this.remaining = url;
  1138. }
  1139. UrlParser.prototype.parseRootSegment = function () {
  1140. this.consumeOptional('/');
  1141. if (this.remaining === '' || this.peekStartsWith('?') || this.peekStartsWith('#')) {
  1142. return new UrlSegmentGroup([], {});
  1143. }
  1144. // The root segment group never has segments
  1145. return new UrlSegmentGroup([], this.parseChildren());
  1146. };
  1147. UrlParser.prototype.parseQueryParams = function () {
  1148. var params = {};
  1149. if (this.consumeOptional('?')) {
  1150. do {
  1151. this.parseQueryParam(params);
  1152. } while (this.consumeOptional('&'));
  1153. }
  1154. return params;
  1155. };
  1156. UrlParser.prototype.parseFragment = function () {
  1157. return this.consumeOptional('#') ? decodeURIComponent(this.remaining) : null;
  1158. };
  1159. UrlParser.prototype.parseChildren = function () {
  1160. if (this.remaining === '') {
  1161. return {};
  1162. }
  1163. this.consumeOptional('/');
  1164. var segments = [];
  1165. if (!this.peekStartsWith('(')) {
  1166. segments.push(this.parseSegment());
  1167. }
  1168. while (this.peekStartsWith('/') && !this.peekStartsWith('//') && !this.peekStartsWith('/(')) {
  1169. this.capture('/');
  1170. segments.push(this.parseSegment());
  1171. }
  1172. var children = {};
  1173. if (this.peekStartsWith('/(')) {
  1174. this.capture('/');
  1175. children = this.parseParens(true);
  1176. }
  1177. var res = {};
  1178. if (this.peekStartsWith('(')) {
  1179. res = this.parseParens(false);
  1180. }
  1181. if (segments.length > 0 || Object.keys(children).length > 0) {
  1182. res[PRIMARY_OUTLET] = new UrlSegmentGroup(segments, children);
  1183. }
  1184. return res;
  1185. };
  1186. // parse a segment with its matrix parameters
  1187. // ie `name;k1=v1;k2`
  1188. UrlParser.prototype.parseSegment = function () {
  1189. var path = matchSegments(this.remaining);
  1190. if (path === '' && this.peekStartsWith(';')) {
  1191. throw new Error("Empty path url segment cannot have parameters: '" + this.remaining + "'.");
  1192. }
  1193. this.capture(path);
  1194. return new UrlSegment(decode(path), this.parseMatrixParams());
  1195. };
  1196. UrlParser.prototype.parseMatrixParams = function () {
  1197. var params = {};
  1198. while (this.consumeOptional(';')) {
  1199. this.parseParam(params);
  1200. }
  1201. return params;
  1202. };
  1203. UrlParser.prototype.parseParam = function (params) {
  1204. var key = matchSegments(this.remaining);
  1205. if (!key) {
  1206. return;
  1207. }
  1208. this.capture(key);
  1209. var value = '';
  1210. if (this.consumeOptional('=')) {
  1211. var valueMatch = matchSegments(this.remaining);
  1212. if (valueMatch) {
  1213. value = valueMatch;
  1214. this.capture(value);
  1215. }
  1216. }
  1217. params[decode(key)] = decode(value);
  1218. };
  1219. // Parse a single query parameter `name[=value]`
  1220. UrlParser.prototype.parseQueryParam = function (params) {
  1221. var key = matchQueryParams(this.remaining);
  1222. if (!key) {
  1223. return;
  1224. }
  1225. this.capture(key);
  1226. var value = '';
  1227. if (this.consumeOptional('=')) {
  1228. var valueMatch = matchUrlQueryParamValue(this.remaining);
  1229. if (valueMatch) {
  1230. value = valueMatch;
  1231. this.capture(value);
  1232. }
  1233. }
  1234. var decodedKey = decodeQuery(key);
  1235. var decodedVal = decodeQuery(value);
  1236. if (params.hasOwnProperty(decodedKey)) {
  1237. // Append to existing values
  1238. var currentVal = params[decodedKey];
  1239. if (!Array.isArray(currentVal)) {
  1240. currentVal = [currentVal];
  1241. params[decodedKey] = currentVal;
  1242. }
  1243. currentVal.push(decodedVal);
  1244. }
  1245. else {
  1246. // Create a new value
  1247. params[decodedKey] = decodedVal;
  1248. }
  1249. };
  1250. // parse `(a/b//outlet_name:c/d)`
  1251. UrlParser.prototype.parseParens = function (allowPrimary) {
  1252. var segments = {};
  1253. this.capture('(');
  1254. while (!this.consumeOptional(')') && this.remaining.length > 0) {
  1255. var path = matchSegments(this.remaining);
  1256. var next = this.remaining[path.length];
  1257. // if is is not one of these characters, then the segment was unescaped
  1258. // or the group was not closed
  1259. if (next !== '/' && next !== ')' && next !== ';') {
  1260. throw new Error("Cannot parse url '" + this.url + "'");
  1261. }
  1262. var outletName = undefined;
  1263. if (path.indexOf(':') > -1) {
  1264. outletName = path.substr(0, path.indexOf(':'));
  1265. this.capture(outletName);
  1266. this.capture(':');
  1267. }
  1268. else if (allowPrimary) {
  1269. outletName = PRIMARY_OUTLET;
  1270. }
  1271. var children = this.parseChildren();
  1272. segments[outletName] = Object.keys(children).length === 1 ? children[PRIMARY_OUTLET] :
  1273. new UrlSegmentGroup([], children);
  1274. this.consumeOptional('//');
  1275. }
  1276. return segments;
  1277. };
  1278. UrlParser.prototype.peekStartsWith = function (str) { return this.remaining.startsWith(str); };
  1279. // Consumes the prefix when it is present and returns whether it has been consumed
  1280. UrlParser.prototype.consumeOptional = function (str) {
  1281. if (this.peekStartsWith(str)) {
  1282. this.remaining = this.remaining.substring(str.length);
  1283. return true;
  1284. }
  1285. return false;
  1286. };
  1287. UrlParser.prototype.capture = function (str) {
  1288. if (!this.consumeOptional(str)) {
  1289. throw new Error("Expected \"" + str + "\".");
  1290. }
  1291. };
  1292. return UrlParser;
  1293. }());
  1294. /**
  1295. * @license
  1296. * Copyright Google Inc. All Rights Reserved.
  1297. *
  1298. * Use of this source code is governed by an MIT-style license that can be
  1299. * found in the LICENSE file at https://angular.io/license
  1300. */
  1301. var Tree = /** @class */ (function () {
  1302. function Tree(root) {
  1303. this._root = root;
  1304. }
  1305. Object.defineProperty(Tree.prototype, "root", {
  1306. get: function () { return this._root.value; },
  1307. enumerable: true,
  1308. configurable: true
  1309. });
  1310. /**
  1311. * @internal
  1312. */
  1313. Tree.prototype.parent = function (t) {
  1314. var p = this.pathFromRoot(t);
  1315. return p.length > 1 ? p[p.length - 2] : null;
  1316. };
  1317. /**
  1318. * @internal
  1319. */
  1320. Tree.prototype.children = function (t) {
  1321. var n = findNode(t, this._root);
  1322. return n ? n.children.map(function (t) { return t.value; }) : [];
  1323. };
  1324. /**
  1325. * @internal
  1326. */
  1327. Tree.prototype.firstChild = function (t) {
  1328. var n = findNode(t, this._root);
  1329. return n && n.children.length > 0 ? n.children[0].value : null;
  1330. };
  1331. /**
  1332. * @internal
  1333. */
  1334. Tree.prototype.siblings = function (t) {
  1335. var p = findPath(t, this._root);
  1336. if (p.length < 2)
  1337. return [];
  1338. var c = p[p.length - 2].children.map(function (c) { return c.value; });
  1339. return c.filter(function (cc) { return cc !== t; });
  1340. };
  1341. /**
  1342. * @internal
  1343. */
  1344. Tree.prototype.pathFromRoot = function (t) { return findPath(t, this._root).map(function (s) { return s.value; }); };
  1345. return Tree;
  1346. }());
  1347. // DFS for the node matching the value
  1348. function findNode(value, node) {
  1349. var e_1, _a;
  1350. if (value === node.value)
  1351. return node;
  1352. try {
  1353. for (var _b = __values(node.children), _c = _b.next(); !_c.done; _c = _b.next()) {
  1354. var child = _c.value;
  1355. var node_1 = findNode(value, child);
  1356. if (node_1)
  1357. return node_1;
  1358. }
  1359. }
  1360. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  1361. finally {
  1362. try {
  1363. if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
  1364. }
  1365. finally { if (e_1) throw e_1.error; }
  1366. }
  1367. return null;
  1368. }
  1369. // Return the path to the node with the given value using DFS
  1370. function findPath(value, node) {
  1371. var e_2, _a;
  1372. if (value === node.value)
  1373. return [node];
  1374. try {
  1375. for (var _b = __values(node.children), _c = _b.next(); !_c.done; _c = _b.next()) {
  1376. var child = _c.value;
  1377. var path = findPath(value, child);
  1378. if (path.length) {
  1379. path.unshift(node);
  1380. return path;
  1381. }
  1382. }
  1383. }
  1384. catch (e_2_1) { e_2 = { error: e_2_1 }; }
  1385. finally {
  1386. try {
  1387. if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
  1388. }
  1389. finally { if (e_2) throw e_2.error; }
  1390. }
  1391. return [];
  1392. }
  1393. var TreeNode = /** @class */ (function () {
  1394. function TreeNode(value, children) {
  1395. this.value = value;
  1396. this.children = children;
  1397. }
  1398. TreeNode.prototype.toString = function () { return "TreeNode(" + this.value + ")"; };
  1399. return TreeNode;
  1400. }());
  1401. // Return the list of T indexed by outlet name
  1402. function nodeChildrenAsMap(node) {
  1403. var map = {};
  1404. if (node) {
  1405. node.children.forEach(function (child) { return map[child.value.outlet] = child; });
  1406. }
  1407. return map;
  1408. }
  1409. /**
  1410. * @license
  1411. * Copyright Google Inc. All Rights Reserved.
  1412. *
  1413. * Use of this source code is governed by an MIT-style license that can be
  1414. * found in the LICENSE file at https://angular.io/license
  1415. */
  1416. /**
  1417. * @description
  1418. *
  1419. * Represents the state of the router.
  1420. *
  1421. * RouterState is a tree of activated routes. Every node in this tree knows about the "consumed" URL
  1422. * segments, the extracted parameters, and the resolved data.
  1423. *
  1424. * @usageNotes
  1425. * ### Example
  1426. *
  1427. * ```
  1428. * @Component({templateUrl:'template.html'})
  1429. * class MyComponent {
  1430. * constructor(router: Router) {
  1431. * const state: RouterState = router.routerState;
  1432. * const root: ActivatedRoute = state.root;
  1433. * const child = root.firstChild;
  1434. * const id: Observable<string> = child.params.map(p => p.id);
  1435. * //...
  1436. * }
  1437. * }
  1438. * ```
  1439. *
  1440. * See `ActivatedRoute` for more information.
  1441. *
  1442. * @publicApi
  1443. */
  1444. var RouterState = /** @class */ (function (_super) {
  1445. __extends(RouterState, _super);
  1446. /** @internal */
  1447. function RouterState(root,
  1448. /** The current snapshot of the router state */
  1449. snapshot) {
  1450. var _this = _super.call(this, root) || this;
  1451. _this.snapshot = snapshot;
  1452. setRouterState(_this, root);
  1453. return _this;
  1454. }
  1455. RouterState.prototype.toString = function () { return this.snapshot.toString(); };
  1456. return RouterState;
  1457. }(Tree));
  1458. function createEmptyState(urlTree, rootComponent) {
  1459. var snapshot = createEmptyStateSnapshot(urlTree, rootComponent);
  1460. var emptyUrl = new BehaviorSubject([new UrlSegment('', {})]);
  1461. var emptyParams = new BehaviorSubject({});
  1462. var emptyData = new BehaviorSubject({});
  1463. var emptyQueryParams = new BehaviorSubject({});
  1464. var fragment = new BehaviorSubject('');
  1465. var activated = new ActivatedRoute(emptyUrl, emptyParams, emptyQueryParams, fragment, emptyData, PRIMARY_OUTLET, rootComponent, snapshot.root);
  1466. activated.snapshot = snapshot.root;
  1467. return new RouterState(new TreeNode(activated, []), snapshot);
  1468. }
  1469. function createEmptyStateSnapshot(urlTree, rootComponent) {
  1470. var emptyParams = {};
  1471. var emptyData = {};
  1472. var emptyQueryParams = {};
  1473. var fragment = '';
  1474. var activated = new ActivatedRouteSnapshot([], emptyParams, emptyQueryParams, fragment, emptyData, PRIMARY_OUTLET, rootComponent, null, urlTree.root, -1, {});
  1475. return new RouterStateSnapshot('', new TreeNode(activated, []));
  1476. }
  1477. /**
  1478. * @description
  1479. *
  1480. * Contains the information about a route associated with a component loaded in an
  1481. * outlet. An `ActivatedRoute` can also be used to traverse the router state tree.
  1482. *
  1483. * {@example router/activated-route/module.ts region="activated-route"
  1484. * header="activated-route.component.ts" linenums="false"}
  1485. *
  1486. * @publicApi
  1487. */
  1488. var ActivatedRoute = /** @class */ (function () {
  1489. /** @internal */
  1490. function ActivatedRoute(
  1491. /** An observable of the URL segments matched by this route */
  1492. url,
  1493. /** An observable of the matrix parameters scoped to this route */
  1494. params,
  1495. /** An observable of the query parameters shared by all the routes */
  1496. queryParams,
  1497. /** An observable of the URL fragment shared by all the routes */
  1498. fragment,
  1499. /** An observable of the static and resolved data of this route. */
  1500. data,
  1501. /** The outlet name of the route. It's a constant */
  1502. outlet,
  1503. /** The component of the route. It's a constant */
  1504. // TODO(vsavkin): remove |string
  1505. component, futureSnapshot) {
  1506. this.url = url;
  1507. this.params = params;
  1508. this.queryParams = queryParams;
  1509. this.fragment = fragment;
  1510. this.data = data;
  1511. this.outlet = outlet;
  1512. this.component = component;
  1513. this._futureSnapshot = futureSnapshot;
  1514. }
  1515. Object.defineProperty(ActivatedRoute.prototype, "routeConfig", {
  1516. /** The configuration used to match this route */
  1517. get: function () { return this._futureSnapshot.routeConfig; },
  1518. enumerable: true,
  1519. configurable: true
  1520. });
  1521. Object.defineProperty(ActivatedRoute.prototype, "root", {
  1522. /** The root of the router state */
  1523. get: function () { return this._routerState.root; },
  1524. enumerable: true,
  1525. configurable: true
  1526. });
  1527. Object.defineProperty(ActivatedRoute.prototype, "parent", {
  1528. /** The parent of this route in the router state tree */
  1529. get: function () { return this._routerState.parent(this); },
  1530. enumerable: true,
  1531. configurable: true
  1532. });
  1533. Object.defineProperty(ActivatedRoute.prototype, "firstChild", {
  1534. /** The first child of this route in the router state tree */
  1535. get: function () { return this._routerState.firstChild(this); },
  1536. enumerable: true,
  1537. configurable: true
  1538. });
  1539. Object.defineProperty(ActivatedRoute.prototype, "children", {
  1540. /** The children of this route in the router state tree */
  1541. get: function () { return this._routerState.children(this); },
  1542. enumerable: true,
  1543. configurable: true
  1544. });
  1545. Object.defineProperty(ActivatedRoute.prototype, "pathFromRoot", {
  1546. /** The path from the root of the router state tree to this route */
  1547. get: function () { return this._routerState.pathFromRoot(this); },
  1548. enumerable: true,
  1549. configurable: true
  1550. });
  1551. Object.defineProperty(ActivatedRoute.prototype, "paramMap", {
  1552. get: function () {
  1553. if (!this._paramMap) {
  1554. this._paramMap = this.params.pipe(map(function (p) { return convertToParamMap(p); }));
  1555. }
  1556. return this._paramMap;
  1557. },
  1558. enumerable: true,
  1559. configurable: true
  1560. });
  1561. Object.defineProperty(ActivatedRoute.prototype, "queryParamMap", {
  1562. get: function () {
  1563. if (!this._queryParamMap) {
  1564. this._queryParamMap =
  1565. this.queryParams.pipe(map(function (p) { return convertToParamMap(p); }));
  1566. }
  1567. return this._queryParamMap;
  1568. },
  1569. enumerable: true,
  1570. configurable: true
  1571. });
  1572. ActivatedRoute.prototype.toString = function () {
  1573. return this.snapshot ? this.snapshot.toString() : "Future(" + this._futureSnapshot + ")";
  1574. };
  1575. return ActivatedRoute;
  1576. }());
  1577. /**
  1578. * Returns the inherited params, data, and resolve for a given route.
  1579. * By default, this only inherits values up to the nearest path-less or component-less route.
  1580. * @internal
  1581. */
  1582. function inheritedParamsDataResolve(route, paramsInheritanceStrategy) {
  1583. if (paramsInheritanceStrategy === void 0) { paramsInheritanceStrategy = 'emptyOnly'; }
  1584. var pathFromRoot = route.pathFromRoot;
  1585. var inheritingStartingFrom = 0;
  1586. if (paramsInheritanceStrategy !== 'always') {
  1587. inheritingStartingFrom = pathFromRoot.length - 1;
  1588. while (inheritingStartingFrom >= 1) {
  1589. var current = pathFromRoot[inheritingStartingFrom];
  1590. var parent_1 = pathFromRoot[inheritingStartingFrom - 1];
  1591. // current route is an empty path => inherits its parent's params and data
  1592. if (current.routeConfig && current.routeConfig.path === '') {
  1593. inheritingStartingFrom--;
  1594. // parent is componentless => current route should inherit its params and data
  1595. }
  1596. else if (!parent_1.component) {
  1597. inheritingStartingFrom--;
  1598. }
  1599. else {
  1600. break;
  1601. }
  1602. }
  1603. }
  1604. return flattenInherited(pathFromRoot.slice(inheritingStartingFrom));
  1605. }
  1606. /** @internal */
  1607. function flattenInherited(pathFromRoot) {
  1608. return pathFromRoot.reduce(function (res, curr) {
  1609. var params = __assign({}, res.params, curr.params);
  1610. var data = __assign({}, res.data, curr.data);
  1611. var resolve = __assign({}, res.resolve, curr._resolvedData);
  1612. return { params: params, data: data, resolve: resolve };
  1613. }, { params: {}, data: {}, resolve: {} });
  1614. }
  1615. /**
  1616. * @description
  1617. *
  1618. * Contains the information about a route associated with a component loaded in an
  1619. * outlet at a particular moment in time. ActivatedRouteSnapshot can also be used to
  1620. * traverse the router state tree.
  1621. *
  1622. * ```
  1623. * @Component({templateUrl:'./my-component.html'})
  1624. * class MyComponent {
  1625. * constructor(route: ActivatedRoute) {
  1626. * const id: string = route.snapshot.params.id;
  1627. * const url: string = route.snapshot.url.join('');
  1628. * const user = route.snapshot.data.user;
  1629. * }
  1630. * }
  1631. * ```
  1632. *
  1633. * @publicApi
  1634. */
  1635. var ActivatedRouteSnapshot = /** @class */ (function () {
  1636. /** @internal */
  1637. function ActivatedRouteSnapshot(
  1638. /** The URL segments matched by this route */
  1639. url,
  1640. /** The matrix parameters scoped to this route */
  1641. params,
  1642. /** The query parameters shared by all the routes */
  1643. queryParams,
  1644. /** The URL fragment shared by all the routes */
  1645. fragment,
  1646. /** The static and resolved data of this route */
  1647. data,
  1648. /** The outlet name of the route */
  1649. outlet,
  1650. /** The component of the route */
  1651. component, routeConfig, urlSegment, lastPathIndex, resolve) {
  1652. this.url = url;
  1653. this.params = params;
  1654. this.queryParams = queryParams;
  1655. this.fragment = fragment;
  1656. this.data = data;
  1657. this.outlet = outlet;
  1658. this.component = component;
  1659. this.routeConfig = routeConfig;
  1660. this._urlSegment = urlSegment;
  1661. this._lastPathIndex = lastPathIndex;
  1662. this._resolve = resolve;
  1663. }
  1664. Object.defineProperty(ActivatedRouteSnapshot.prototype, "root", {
  1665. /** The root of the router state */
  1666. get: function () { return this._routerState.root; },
  1667. enumerable: true,
  1668. configurable: true
  1669. });
  1670. Object.defineProperty(ActivatedRouteSnapshot.prototype, "parent", {
  1671. /** The parent of this route in the router state tree */
  1672. get: function () { return this._routerState.parent(this); },
  1673. enumerable: true,
  1674. configurable: true
  1675. });
  1676. Object.defineProperty(ActivatedRouteSnapshot.prototype, "firstChild", {
  1677. /** The first child of this route in the router state tree */
  1678. get: function () { return this._routerState.firstChild(this); },
  1679. enumerable: true,
  1680. configurable: true
  1681. });
  1682. Object.defineProperty(ActivatedRouteSnapshot.prototype, "children", {
  1683. /** The children of this route in the router state tree */
  1684. get: function () { return this._routerState.children(this); },
  1685. enumerable: true,
  1686. configurable: true
  1687. });
  1688. Object.defineProperty(ActivatedRouteSnapshot.prototype, "pathFromRoot", {
  1689. /** The path from the root of the router state tree to this route */
  1690. get: function () { return this._routerState.pathFromRoot(this); },
  1691. enumerable: true,
  1692. configurable: true
  1693. });
  1694. Object.defineProperty(ActivatedRouteSnapshot.prototype, "paramMap", {
  1695. get: function () {
  1696. if (!this._paramMap) {
  1697. this._paramMap = convertToParamMap(this.params);
  1698. }
  1699. return this._paramMap;
  1700. },
  1701. enumerable: true,
  1702. configurable: true
  1703. });
  1704. Object.defineProperty(ActivatedRouteSnapshot.prototype, "queryParamMap", {
  1705. get: function () {
  1706. if (!this._queryParamMap) {
  1707. this._queryParamMap = convertToParamMap(this.queryParams);
  1708. }
  1709. return this._queryParamMap;
  1710. },
  1711. enumerable: true,
  1712. configurable: true
  1713. });
  1714. ActivatedRouteSnapshot.prototype.toString = function () {
  1715. var url = this.url.map(function (segment) { return segment.toString(); }).join('/');
  1716. var matched = this.routeConfig ? this.routeConfig.path : '';
  1717. return "Route(url:'" + url + "', path:'" + matched + "')";
  1718. };
  1719. return ActivatedRouteSnapshot;
  1720. }());
  1721. /**
  1722. * @description
  1723. *
  1724. * Represents the state of the router at a moment in time.
  1725. *
  1726. * This is a tree of activated route snapshots. Every node in this tree knows about
  1727. * the "consumed" URL segments, the extracted parameters, and the resolved data.
  1728. *
  1729. * @usageNotes
  1730. * ### Example
  1731. *
  1732. * ```
  1733. * @Component({templateUrl:'template.html'})
  1734. * class MyComponent {
  1735. * constructor(router: Router) {
  1736. * const state: RouterState = router.routerState;
  1737. * const snapshot: RouterStateSnapshot = state.snapshot;
  1738. * const root: ActivatedRouteSnapshot = snapshot.root;
  1739. * const child = root.firstChild;
  1740. * const id: Observable<string> = child.params.map(p => p.id);
  1741. * //...
  1742. * }
  1743. * }
  1744. * ```
  1745. *
  1746. * @publicApi
  1747. */
  1748. var RouterStateSnapshot = /** @class */ (function (_super) {
  1749. __extends(RouterStateSnapshot, _super);
  1750. /** @internal */
  1751. function RouterStateSnapshot(
  1752. /** The url from which this snapshot was created */
  1753. url, root) {
  1754. var _this = _super.call(this, root) || this;
  1755. _this.url = url;
  1756. setRouterState(_this, root);
  1757. return _this;
  1758. }
  1759. RouterStateSnapshot.prototype.toString = function () { return serializeNode(this._root); };
  1760. return RouterStateSnapshot;
  1761. }(Tree));
  1762. function setRouterState(state, node) {
  1763. node.value._routerState = state;
  1764. node.children.forEach(function (c) { return setRouterState(state, c); });
  1765. }
  1766. function serializeNode(node) {
  1767. var c = node.children.length > 0 ? " { " + node.children.map(serializeNode).join(', ') + " } " : '';
  1768. return "" + node.value + c;
  1769. }
  1770. /**
  1771. * The expectation is that the activate route is created with the right set of parameters.
  1772. * So we push new values into the observables only when they are not the initial values.
  1773. * And we detect that by checking if the snapshot field is set.
  1774. */
  1775. function advanceActivatedRoute(route) {
  1776. if (route.snapshot) {
  1777. var currentSnapshot = route.snapshot;
  1778. var nextSnapshot = route._futureSnapshot;
  1779. route.snapshot = nextSnapshot;
  1780. if (!shallowEqual(currentSnapshot.queryParams, nextSnapshot.queryParams)) {
  1781. route.queryParams.next(nextSnapshot.queryParams);
  1782. }
  1783. if (currentSnapshot.fragment !== nextSnapshot.fragment) {
  1784. route.fragment.next(nextSnapshot.fragment);
  1785. }
  1786. if (!shallowEqual(currentSnapshot.params, nextSnapshot.params)) {
  1787. route.params.next(nextSnapshot.params);
  1788. }
  1789. if (!shallowEqualArrays(currentSnapshot.url, nextSnapshot.url)) {
  1790. route.url.next(nextSnapshot.url);
  1791. }
  1792. if (!shallowEqual(currentSnapshot.data, nextSnapshot.data)) {
  1793. route.data.next(nextSnapshot.data);
  1794. }
  1795. }
  1796. else {
  1797. route.snapshot = route._futureSnapshot;
  1798. // this is for resolved data
  1799. route.data.next(route._futureSnapshot.data);
  1800. }
  1801. }
  1802. function equalParamsAndUrlSegments(a, b) {
  1803. var equalUrlParams = shallowEqual(a.params, b.params) && equalSegments(a.url, b.url);
  1804. var parentsMismatch = !a.parent !== !b.parent;
  1805. return equalUrlParams && !parentsMismatch &&
  1806. (!a.parent || equalParamsAndUrlSegments(a.parent, b.parent));
  1807. }
  1808. /**
  1809. * @license
  1810. * Copyright Google Inc. All Rights Reserved.
  1811. *
  1812. * Use of this source code is governed by an MIT-style license that can be
  1813. * found in the LICENSE file at https://angular.io/license
  1814. */
  1815. function createRouterState(routeReuseStrategy, curr, prevState) {
  1816. var root = createNode(routeReuseStrategy, curr._root, prevState ? prevState._root : undefined);
  1817. return new RouterState(root, curr);
  1818. }
  1819. function createNode(routeReuseStrategy, curr, prevState) {
  1820. // reuse an activated route that is currently displayed on the screen
  1821. if (prevState && routeReuseStrategy.shouldReuseRoute(curr.value, prevState.value.snapshot)) {
  1822. var value = prevState.value;
  1823. value._futureSnapshot = curr.value;
  1824. var children = createOrReuseChildren(routeReuseStrategy, curr, prevState);
  1825. return new TreeNode(value, children);
  1826. // retrieve an activated route that is used to be displayed, but is not currently displayed
  1827. }
  1828. else {
  1829. var detachedRouteHandle = routeReuseStrategy.retrieve(curr.value);
  1830. if (detachedRouteHandle) {
  1831. var tree = detachedRouteHandle.route;
  1832. setFutureSnapshotsOfActivatedRoutes(curr, tree);
  1833. return tree;
  1834. }
  1835. else {
  1836. var value = createActivatedRoute(curr.value);
  1837. var children = curr.children.map(function (c) { return createNode(routeReuseStrategy, c); });
  1838. return new TreeNode(value, children);
  1839. }
  1840. }
  1841. }
  1842. function setFutureSnapshotsOfActivatedRoutes(curr, result) {
  1843. if (curr.value.routeConfig !== result.value.routeConfig) {
  1844. throw new Error('Cannot reattach ActivatedRouteSnapshot created from a different route');
  1845. }
  1846. if (curr.children.length !== result.children.length) {
  1847. throw new Error('Cannot reattach ActivatedRouteSnapshot with a different number of children');
  1848. }
  1849. result.value._futureSnapshot = curr.value;
  1850. for (var i = 0; i < curr.children.length; ++i) {
  1851. setFutureSnapshotsOfActivatedRoutes(curr.children[i], result.children[i]);
  1852. }
  1853. }
  1854. function createOrReuseChildren(routeReuseStrategy, curr, prevState) {
  1855. return curr.children.map(function (child) {
  1856. var e_1, _a;
  1857. try {
  1858. for (var _b = __values(prevState.children), _c = _b.next(); !_c.done; _c = _b.next()) {
  1859. var p = _c.value;
  1860. if (routeReuseStrategy.shouldReuseRoute(p.value.snapshot, child.value)) {
  1861. return createNode(routeReuseStrategy, child, p);
  1862. }
  1863. }
  1864. }
  1865. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  1866. finally {
  1867. try {
  1868. if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
  1869. }
  1870. finally { if (e_1) throw e_1.error; }
  1871. }
  1872. return createNode(routeReuseStrategy, child);
  1873. });
  1874. }
  1875. function createActivatedRoute(c) {
  1876. 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);
  1877. }
  1878. /**
  1879. * @license
  1880. * Copyright Google Inc. All Rights Reserved.
  1881. *
  1882. * Use of this source code is governed by an MIT-style license that can be
  1883. * found in the LICENSE file at https://angular.io/license
  1884. */
  1885. function createUrlTree(route, urlTree, commands, queryParams, fragment) {
  1886. if (commands.length === 0) {
  1887. return tree(urlTree.root, urlTree.root, urlTree, queryParams, fragment);
  1888. }
  1889. var nav = computeNavigation(commands);
  1890. if (nav.toRoot()) {
  1891. return tree(urlTree.root, new UrlSegmentGroup([], {}), urlTree, queryParams, fragment);
  1892. }
  1893. var startingPosition = findStartingPosition(nav, urlTree, route);
  1894. var segmentGroup = startingPosition.processChildren ?
  1895. updateSegmentGroupChildren(startingPosition.segmentGroup, startingPosition.index, nav.commands) :
  1896. updateSegmentGroup(startingPosition.segmentGroup, startingPosition.index, nav.commands);
  1897. return tree(startingPosition.segmentGroup, segmentGroup, urlTree, queryParams, fragment);
  1898. }
  1899. function isMatrixParams(command) {
  1900. return typeof command === 'object' && command != null && !command.outlets && !command.segmentPath;
  1901. }
  1902. function tree(oldSegmentGroup, newSegmentGroup, urlTree, queryParams, fragment) {
  1903. var qp = {};
  1904. if (queryParams) {
  1905. forEach(queryParams, function (value, name) {
  1906. qp[name] = Array.isArray(value) ? value.map(function (v) { return "" + v; }) : "" + value;
  1907. });
  1908. }
  1909. if (urlTree.root === oldSegmentGroup) {
  1910. return new UrlTree(newSegmentGroup, qp, fragment);
  1911. }
  1912. return new UrlTree(replaceSegment(urlTree.root, oldSegmentGroup, newSegmentGroup), qp, fragment);
  1913. }
  1914. function replaceSegment(current, oldSegment, newSegment) {
  1915. var children = {};
  1916. forEach(current.children, function (c, outletName) {
  1917. if (c === oldSegment) {
  1918. children[outletName] = newSegment;
  1919. }
  1920. else {
  1921. children[outletName] = replaceSegment(c, oldSegment, newSegment);
  1922. }
  1923. });
  1924. return new UrlSegmentGroup(current.segments, children);
  1925. }
  1926. var Navigation = /** @class */ (function () {
  1927. function Navigation(isAbsolute, numberOfDoubleDots, commands) {
  1928. this.isAbsolute = isAbsolute;
  1929. this.numberOfDoubleDots = numberOfDoubleDots;
  1930. this.commands = commands;
  1931. if (isAbsolute && commands.length > 0 && isMatrixParams(commands[0])) {
  1932. throw new Error('Root segment cannot have matrix parameters');
  1933. }
  1934. var cmdWithOutlet = commands.find(function (c) { return typeof c === 'object' && c != null && c.outlets; });
  1935. if (cmdWithOutlet && cmdWithOutlet !== last(commands)) {
  1936. throw new Error('{outlets:{}} has to be the last command');
  1937. }
  1938. }
  1939. Navigation.prototype.toRoot = function () {
  1940. return this.isAbsolute && this.commands.length === 1 && this.commands[0] == '/';
  1941. };
  1942. return Navigation;
  1943. }());
  1944. /** Transforms commands to a normalized `Navigation` */
  1945. function computeNavigation(commands) {
  1946. if ((typeof commands[0] === 'string') && commands.length === 1 && commands[0] === '/') {
  1947. return new Navigation(true, 0, commands);
  1948. }
  1949. var numberOfDoubleDots = 0;
  1950. var isAbsolute = false;
  1951. var res = commands.reduce(function (res, cmd, cmdIdx) {
  1952. if (typeof cmd === 'object' && cmd != null) {
  1953. if (cmd.outlets) {
  1954. var outlets_1 = {};
  1955. forEach(cmd.outlets, function (commands, name) {
  1956. outlets_1[name] = typeof commands === 'string' ? commands.split('/') : commands;
  1957. });
  1958. return __spread(res, [{ outlets: outlets_1 }]);
  1959. }
  1960. if (cmd.segmentPath) {
  1961. return __spread(res, [cmd.segmentPath]);
  1962. }
  1963. }
  1964. if (!(typeof cmd === 'string')) {
  1965. return __spread(res, [cmd]);
  1966. }
  1967. if (cmdIdx === 0) {
  1968. cmd.split('/').forEach(function (urlPart, partIndex) {
  1969. if (partIndex == 0 && urlPart === '.') ;
  1970. else if (partIndex == 0 && urlPart === '') { // '/a'
  1971. isAbsolute = true;
  1972. }
  1973. else if (urlPart === '..') { // '../a'
  1974. numberOfDoubleDots++;
  1975. }
  1976. else if (urlPart != '') {
  1977. res.push(urlPart);
  1978. }
  1979. });
  1980. return res;
  1981. }
  1982. return __spread(res, [cmd]);
  1983. }, []);
  1984. return new Navigation(isAbsolute, numberOfDoubleDots, res);
  1985. }
  1986. var Position = /** @class */ (function () {
  1987. function Position(segmentGroup, processChildren, index) {
  1988. this.segmentGroup = segmentGroup;
  1989. this.processChildren = processChildren;
  1990. this.index = index;
  1991. }
  1992. return Position;
  1993. }());
  1994. function findStartingPosition(nav, tree, route) {
  1995. if (nav.isAbsolute) {
  1996. return new Position(tree.root, true, 0);
  1997. }
  1998. if (route.snapshot._lastPathIndex === -1) {
  1999. return new Position(route.snapshot._urlSegment, true, 0);
  2000. }
  2001. var modifier = isMatrixParams(nav.commands[0]) ? 0 : 1;
  2002. var index = route.snapshot._lastPathIndex + modifier;
  2003. return createPositionApplyingDoubleDots(route.snapshot._urlSegment, index, nav.numberOfDoubleDots);
  2004. }
  2005. function createPositionApplyingDoubleDots(group, index, numberOfDoubleDots) {
  2006. var g = group;
  2007. var ci = index;
  2008. var dd = numberOfDoubleDots;
  2009. while (dd > ci) {
  2010. dd -= ci;
  2011. g = g.parent;
  2012. if (!g) {
  2013. throw new Error('Invalid number of \'../\'');
  2014. }
  2015. ci = g.segments.length;
  2016. }
  2017. return new Position(g, false, ci - dd);
  2018. }
  2019. function getPath(command) {
  2020. if (typeof command === 'object' && command != null && command.outlets) {
  2021. return command.outlets[PRIMARY_OUTLET];
  2022. }
  2023. return "" + command;
  2024. }
  2025. function getOutlets(commands) {
  2026. var _a, _b;
  2027. if (!(typeof commands[0] === 'object'))
  2028. return _a = {}, _a[PRIMARY_OUTLET] = commands, _a;
  2029. if (commands[0].outlets === undefined)
  2030. return _b = {}, _b[PRIMARY_OUTLET] = commands, _b;
  2031. return commands[0].outlets;
  2032. }
  2033. function updateSegmentGroup(segmentGroup, startIndex, commands) {
  2034. if (!segmentGroup) {
  2035. segmentGroup = new UrlSegmentGroup([], {});
  2036. }
  2037. if (segmentGroup.segments.length === 0 && segmentGroup.hasChildren()) {
  2038. return updateSegmentGroupChildren(segmentGroup, startIndex, commands);
  2039. }
  2040. var m = prefixedWith(segmentGroup, startIndex, commands);
  2041. var slicedCommands = commands.slice(m.commandIndex);
  2042. if (m.match && m.pathIndex < segmentGroup.segments.length) {
  2043. var g = new UrlSegmentGroup(segmentGroup.segments.slice(0, m.pathIndex), {});
  2044. g.children[PRIMARY_OUTLET] =
  2045. new UrlSegmentGroup(segmentGroup.segments.slice(m.pathIndex), segmentGroup.children);
  2046. return updateSegmentGroupChildren(g, 0, slicedCommands);
  2047. }
  2048. else if (m.match && slicedCommands.length === 0) {
  2049. return new UrlSegmentGroup(segmentGroup.segments, {});
  2050. }
  2051. else if (m.match && !segmentGroup.hasChildren()) {
  2052. return createNewSegmentGroup(segmentGroup, startIndex, commands);
  2053. }
  2054. else if (m.match) {
  2055. return updateSegmentGroupChildren(segmentGroup, 0, slicedCommands);
  2056. }
  2057. else {
  2058. return createNewSegmentGroup(segmentGroup, startIndex, commands);
  2059. }
  2060. }
  2061. function updateSegmentGroupChildren(segmentGroup, startIndex, commands) {
  2062. if (commands.length === 0) {
  2063. return new UrlSegmentGroup(segmentGroup.segments, {});
  2064. }
  2065. else {
  2066. var outlets_2 = getOutlets(commands);
  2067. var children_1 = {};
  2068. forEach(outlets_2, function (commands, outlet) {
  2069. if (commands !== null) {
  2070. children_1[outlet] = updateSegmentGroup(segmentGroup.children[outlet], startIndex, commands);
  2071. }
  2072. });
  2073. forEach(segmentGroup.children, function (child, childOutlet) {
  2074. if (outlets_2[childOutlet] === undefined) {
  2075. children_1[childOutlet] = child;
  2076. }
  2077. });
  2078. return new UrlSegmentGroup(segmentGroup.segments, children_1);
  2079. }
  2080. }
  2081. function prefixedWith(segmentGroup, startIndex, commands) {
  2082. var currentCommandIndex = 0;
  2083. var currentPathIndex = startIndex;
  2084. var noMatch = { match: false, pathIndex: 0, commandIndex: 0 };
  2085. while (currentPathIndex < segmentGroup.segments.length) {
  2086. if (currentCommandIndex >= commands.length)
  2087. return noMatch;
  2088. var path = segmentGroup.segments[currentPathIndex];
  2089. var curr = getPath(commands[currentCommandIndex]);
  2090. var next = currentCommandIndex < commands.length - 1 ? commands[currentCommandIndex + 1] : null;
  2091. if (currentPathIndex > 0 && curr === undefined)
  2092. break;
  2093. if (curr && next && (typeof next === 'object') && next.outlets === undefined) {
  2094. if (!compare(curr, next, path))
  2095. return noMatch;
  2096. currentCommandIndex += 2;
  2097. }
  2098. else {
  2099. if (!compare(curr, {}, path))
  2100. return noMatch;
  2101. currentCommandIndex++;
  2102. }
  2103. currentPathIndex++;
  2104. }
  2105. return { match: true, pathIndex: currentPathIndex, commandIndex: currentCommandIndex };
  2106. }
  2107. function createNewSegmentGroup(segmentGroup, startIndex, commands) {
  2108. var paths = segmentGroup.segments.slice(0, startIndex);
  2109. var i = 0;
  2110. while (i < commands.length) {
  2111. if (typeof commands[i] === 'object' && commands[i].outlets !== undefined) {
  2112. var children = createNewSegmentChildren(commands[i].outlets);
  2113. return new UrlSegmentGroup(paths, children);
  2114. }
  2115. // if we start with an object literal, we need to reuse the path part from the segment
  2116. if (i === 0 && isMatrixParams(commands[0])) {
  2117. var p = segmentGroup.segments[startIndex];
  2118. paths.push(new UrlSegment(p.path, commands[0]));
  2119. i++;
  2120. continue;
  2121. }
  2122. var curr = getPath(commands[i]);
  2123. var next = (i < commands.length - 1) ? commands[i + 1] : null;
  2124. if (curr && next && isMatrixParams(next)) {
  2125. paths.push(new UrlSegment(curr, stringify(next)));
  2126. i += 2;
  2127. }
  2128. else {
  2129. paths.push(new UrlSegment(curr, {}));
  2130. i++;
  2131. }
  2132. }
  2133. return new UrlSegmentGroup(paths, {});
  2134. }
  2135. function createNewSegmentChildren(outlets) {
  2136. var children = {};
  2137. forEach(outlets, function (commands, outlet) {
  2138. if (commands !== null) {
  2139. children[outlet] = createNewSegmentGroup(new UrlSegmentGroup([], {}), 0, commands);
  2140. }
  2141. });
  2142. return children;
  2143. }
  2144. function stringify(params) {
  2145. var res = {};
  2146. forEach(params, function (v, k) { return res[k] = "" + v; });
  2147. return res;
  2148. }
  2149. function compare(path, params, segment) {
  2150. return path == segment.path && shallowEqual(params, segment.parameters);
  2151. }
  2152. /**
  2153. * @license
  2154. * Copyright Google Inc. All Rights Reserved.
  2155. *
  2156. * Use of this source code is governed by an MIT-style license that can be
  2157. * found in the LICENSE file at https://angular.io/license
  2158. */
  2159. var activateRoutes = function (rootContexts, routeReuseStrategy, forwardEvent) {
  2160. return map(function (t) {
  2161. new ActivateRoutes(routeReuseStrategy, t.targetRouterState, t.currentRouterState, forwardEvent)
  2162. .activate(rootContexts);
  2163. return t;
  2164. });
  2165. };
  2166. var ActivateRoutes = /** @class */ (function () {
  2167. function ActivateRoutes(routeReuseStrategy, futureState, currState, forwardEvent) {
  2168. this.routeReuseStrategy = routeReuseStrategy;
  2169. this.futureState = futureState;
  2170. this.currState = currState;
  2171. this.forwardEvent = forwardEvent;
  2172. }
  2173. ActivateRoutes.prototype.activate = function (parentContexts) {
  2174. var futureRoot = this.futureState._root;
  2175. var currRoot = this.currState ? this.currState._root : null;
  2176. this.deactivateChildRoutes(futureRoot, currRoot, parentContexts);
  2177. advanceActivatedRoute(this.futureState.root);
  2178. this.activateChildRoutes(futureRoot, currRoot, parentContexts);
  2179. };
  2180. // De-activate the child route that are not re-used for the future state
  2181. ActivateRoutes.prototype.deactivateChildRoutes = function (futureNode, currNode, contexts) {
  2182. var _this = this;
  2183. var children = nodeChildrenAsMap(currNode);
  2184. // Recurse on the routes active in the future state to de-activate deeper children
  2185. futureNode.children.forEach(function (futureChild) {
  2186. var childOutletName = futureChild.value.outlet;
  2187. _this.deactivateRoutes(futureChild, children[childOutletName], contexts);
  2188. delete children[childOutletName];
  2189. });
  2190. // De-activate the routes that will not be re-used
  2191. forEach(children, function (v, childName) {
  2192. _this.deactivateRouteAndItsChildren(v, contexts);
  2193. });
  2194. };
  2195. ActivateRoutes.prototype.deactivateRoutes = function (futureNode, currNode, parentContext) {
  2196. var future = futureNode.value;
  2197. var curr = currNode ? currNode.value : null;
  2198. if (future === curr) {
  2199. // Reusing the node, check to see if the children need to be de-activated
  2200. if (future.component) {
  2201. // If we have a normal route, we need to go through an outlet.
  2202. var context = parentContext.getContext(future.outlet);
  2203. if (context) {
  2204. this.deactivateChildRoutes(futureNode, currNode, context.children);
  2205. }
  2206. }
  2207. else {
  2208. // if we have a componentless route, we recurse but keep the same outlet map.
  2209. this.deactivateChildRoutes(futureNode, currNode, parentContext);
  2210. }
  2211. }
  2212. else {
  2213. if (curr) {
  2214. // Deactivate the current route which will not be re-used
  2215. this.deactivateRouteAndItsChildren(currNode, parentContext);
  2216. }
  2217. }
  2218. };
  2219. ActivateRoutes.prototype.deactivateRouteAndItsChildren = function (route, parentContexts) {
  2220. if (this.routeReuseStrategy.shouldDetach(route.value.snapshot)) {
  2221. this.detachAndStoreRouteSubtree(route, parentContexts);
  2222. }
  2223. else {
  2224. this.deactivateRouteAndOutlet(route, parentContexts);
  2225. }
  2226. };
  2227. ActivateRoutes.prototype.detachAndStoreRouteSubtree = function (route, parentContexts) {
  2228. var context = parentContexts.getContext(route.value.outlet);
  2229. if (context && context.outlet) {
  2230. var componentRef = context.outlet.detach();
  2231. var contexts = context.children.onOutletDeactivated();
  2232. this.routeReuseStrategy.store(route.value.snapshot, { componentRef: componentRef, route: route, contexts: contexts });
  2233. }
  2234. };
  2235. ActivateRoutes.prototype.deactivateRouteAndOutlet = function (route, parentContexts) {
  2236. var _this = this;
  2237. var context = parentContexts.getContext(route.value.outlet);
  2238. if (context) {
  2239. var children = nodeChildrenAsMap(route);
  2240. var contexts_1 = route.value.component ? context.children : parentContexts;
  2241. forEach(children, function (v, k) { return _this.deactivateRouteAndItsChildren(v, contexts_1); });
  2242. if (context.outlet) {
  2243. // Destroy the component
  2244. context.outlet.deactivate();
  2245. // Destroy the contexts for all the outlets that were in the component
  2246. context.children.onOutletDeactivated();
  2247. }
  2248. }
  2249. };
  2250. ActivateRoutes.prototype.activateChildRoutes = function (futureNode, currNode, contexts) {
  2251. var _this = this;
  2252. var children = nodeChildrenAsMap(currNode);
  2253. futureNode.children.forEach(function (c) {
  2254. _this.activateRoutes(c, children[c.value.outlet], contexts);
  2255. _this.forwardEvent(new ActivationEnd(c.value.snapshot));
  2256. });
  2257. if (futureNode.children.length) {
  2258. this.forwardEvent(new ChildActivationEnd(futureNode.value.snapshot));
  2259. }
  2260. };
  2261. ActivateRoutes.prototype.activateRoutes = function (futureNode, currNode, parentContexts) {
  2262. var future = futureNode.value;
  2263. var curr = currNode ? currNode.value : null;
  2264. advanceActivatedRoute(future);
  2265. // reusing the node
  2266. if (future === curr) {
  2267. if (future.component) {
  2268. // If we have a normal route, we need to go through an outlet.
  2269. var context = parentContexts.getOrCreateContext(future.outlet);
  2270. this.activateChildRoutes(futureNode, currNode, context.children);
  2271. }
  2272. else {
  2273. // if we have a componentless route, we recurse but keep the same outlet map.
  2274. this.activateChildRoutes(futureNode, currNode, parentContexts);
  2275. }
  2276. }
  2277. else {
  2278. if (future.component) {
  2279. // if we have a normal route, we need to place the component into the outlet and recurse.
  2280. var context = parentContexts.getOrCreateContext(future.outlet);
  2281. if (this.routeReuseStrategy.shouldAttach(future.snapshot)) {
  2282. var stored = this.routeReuseStrategy.retrieve(future.snapshot);
  2283. this.routeReuseStrategy.store(future.snapshot, null);
  2284. context.children.onOutletReAttached(stored.contexts);
  2285. context.attachRef = stored.componentRef;
  2286. context.route = stored.route.value;
  2287. if (context.outlet) {
  2288. // Attach right away when the outlet has already been instantiated
  2289. // Otherwise attach from `RouterOutlet.ngOnInit` when it is instantiated
  2290. context.outlet.attach(stored.componentRef, stored.route.value);
  2291. }
  2292. advanceActivatedRouteNodeAndItsChildren(stored.route);
  2293. }
  2294. else {
  2295. var config = parentLoadedConfig(future.snapshot);
  2296. var cmpFactoryResolver = config ? config.module.componentFactoryResolver : null;
  2297. context.attachRef = null;
  2298. context.route = future;
  2299. context.resolver = cmpFactoryResolver;
  2300. if (context.outlet) {
  2301. // Activate the outlet when it has already been instantiated
  2302. // Otherwise it will get activated from its `ngOnInit` when instantiated
  2303. context.outlet.activateWith(future, cmpFactoryResolver);
  2304. }
  2305. this.activateChildRoutes(futureNode, null, context.children);
  2306. }
  2307. }
  2308. else {
  2309. // if we have a componentless route, we recurse but keep the same outlet map.
  2310. this.activateChildRoutes(futureNode, null, parentContexts);
  2311. }
  2312. }
  2313. };
  2314. return ActivateRoutes;
  2315. }());
  2316. function advanceActivatedRouteNodeAndItsChildren(node) {
  2317. advanceActivatedRoute(node.value);
  2318. node.children.forEach(advanceActivatedRouteNodeAndItsChildren);
  2319. }
  2320. function parentLoadedConfig(snapshot) {
  2321. for (var s = snapshot.parent; s; s = s.parent) {
  2322. var route = s.routeConfig;
  2323. if (route && route._loadedConfig)
  2324. return route._loadedConfig;
  2325. if (route && route.component)
  2326. return null;
  2327. }
  2328. return null;
  2329. }
  2330. /**
  2331. * @license
  2332. * Copyright Google Inc. All Rights Reserved.
  2333. *
  2334. * Use of this source code is governed by an MIT-style license that can be
  2335. * found in the LICENSE file at https://angular.io/license
  2336. */
  2337. /**
  2338. * Simple function check, but generic so type inference will flow. Example:
  2339. *
  2340. * function product(a: number, b: number) {
  2341. * return a * b;
  2342. * }
  2343. *
  2344. * if (isFunction<product>(fn)) {
  2345. * return fn(1, 2);
  2346. * } else {
  2347. * throw "Must provide the `product` function";
  2348. * }
  2349. */
  2350. function isFunction(v) {
  2351. return typeof v === 'function';
  2352. }
  2353. function isBoolean(v) {
  2354. return typeof v === 'boolean';
  2355. }
  2356. function isUrlTree(v) {
  2357. return v instanceof UrlTree;
  2358. }
  2359. function isCanLoad(guard) {
  2360. return guard && isFunction(guard.canLoad);
  2361. }
  2362. function isCanActivate(guard) {
  2363. return guard && isFunction(guard.canActivate);
  2364. }
  2365. function isCanActivateChild(guard) {
  2366. return guard && isFunction(guard.canActivateChild);
  2367. }
  2368. function isCanDeactivate(guard) {
  2369. return guard && isFunction(guard.canDeactivate);
  2370. }
  2371. /**
  2372. * @license
  2373. * Copyright Google Inc. All Rights Reserved.
  2374. *
  2375. * Use of this source code is governed by an MIT-style license that can be
  2376. * found in the LICENSE file at https://angular.io/license
  2377. */
  2378. var NoMatch = /** @class */ (function () {
  2379. function NoMatch(segmentGroup) {
  2380. this.segmentGroup = segmentGroup || null;
  2381. }
  2382. return NoMatch;
  2383. }());
  2384. var AbsoluteRedirect = /** @class */ (function () {
  2385. function AbsoluteRedirect(urlTree) {
  2386. this.urlTree = urlTree;
  2387. }
  2388. return AbsoluteRedirect;
  2389. }());
  2390. function noMatch(segmentGroup) {
  2391. return new Observable(function (obs) { return obs.error(new NoMatch(segmentGroup)); });
  2392. }
  2393. function absoluteRedirect(newTree) {
  2394. return new Observable(function (obs) { return obs.error(new AbsoluteRedirect(newTree)); });
  2395. }
  2396. function namedOutletsRedirect(redirectTo) {
  2397. return new Observable(function (obs) { return obs.error(new Error("Only absolute redirects can have named outlets. redirectTo: '" + redirectTo + "'")); });
  2398. }
  2399. function canLoadFails(route) {
  2400. return new Observable(function (obs) { return obs.error(navigationCancelingError("Cannot load children because the guard of the route \"path: '" + route.path + "'\" returned false")); });
  2401. }
  2402. /**
  2403. * Returns the `UrlTree` with the redirection applied.
  2404. *
  2405. * Lazy modules are loaded along the way.
  2406. */
  2407. function applyRedirects(moduleInjector, configLoader, urlSerializer, urlTree, config) {
  2408. return new ApplyRedirects(moduleInjector, configLoader, urlSerializer, urlTree, config).apply();
  2409. }
  2410. var ApplyRedirects = /** @class */ (function () {
  2411. function ApplyRedirects(moduleInjector, configLoader, urlSerializer, urlTree, config) {
  2412. this.configLoader = configLoader;
  2413. this.urlSerializer = urlSerializer;
  2414. this.urlTree = urlTree;
  2415. this.config = config;
  2416. this.allowRedirects = true;
  2417. this.ngModule = moduleInjector.get(NgModuleRef);
  2418. }
  2419. ApplyRedirects.prototype.apply = function () {
  2420. var _this = this;
  2421. var expanded$ = this.expandSegmentGroup(this.ngModule, this.config, this.urlTree.root, PRIMARY_OUTLET);
  2422. var urlTrees$ = expanded$.pipe(map(function (rootSegmentGroup) { return _this.createUrlTree(rootSegmentGroup, _this.urlTree.queryParams, _this.urlTree.fragment); }));
  2423. return urlTrees$.pipe(catchError(function (e) {
  2424. if (e instanceof AbsoluteRedirect) {
  2425. // after an absolute redirect we do not apply any more redirects!
  2426. _this.allowRedirects = false;
  2427. // we need to run matching, so we can fetch all lazy-loaded modules
  2428. return _this.match(e.urlTree);
  2429. }
  2430. if (e instanceof NoMatch) {
  2431. throw _this.noMatchError(e);
  2432. }
  2433. throw e;
  2434. }));
  2435. };
  2436. ApplyRedirects.prototype.match = function (tree) {
  2437. var _this = this;
  2438. var expanded$ = this.expandSegmentGroup(this.ngModule, this.config, tree.root, PRIMARY_OUTLET);
  2439. var mapped$ = expanded$.pipe(map(function (rootSegmentGroup) {
  2440. return _this.createUrlTree(rootSegmentGroup, tree.queryParams, tree.fragment);
  2441. }));
  2442. return mapped$.pipe(catchError(function (e) {
  2443. if (e instanceof NoMatch) {
  2444. throw _this.noMatchError(e);
  2445. }
  2446. throw e;
  2447. }));
  2448. };
  2449. ApplyRedirects.prototype.noMatchError = function (e) {
  2450. return new Error("Cannot match any routes. URL Segment: '" + e.segmentGroup + "'");
  2451. };
  2452. ApplyRedirects.prototype.createUrlTree = function (rootCandidate, queryParams, fragment) {
  2453. var _a;
  2454. var root = rootCandidate.segments.length > 0 ?
  2455. new UrlSegmentGroup([], (_a = {}, _a[PRIMARY_OUTLET] = rootCandidate, _a)) :
  2456. rootCandidate;
  2457. return new UrlTree(root, queryParams, fragment);
  2458. };
  2459. ApplyRedirects.prototype.expandSegmentGroup = function (ngModule, routes, segmentGroup, outlet) {
  2460. if (segmentGroup.segments.length === 0 && segmentGroup.hasChildren()) {
  2461. return this.expandChildren(ngModule, routes, segmentGroup)
  2462. .pipe(map(function (children) { return new UrlSegmentGroup([], children); }));
  2463. }
  2464. return this.expandSegment(ngModule, segmentGroup, routes, segmentGroup.segments, outlet, true);
  2465. };
  2466. // Recursively expand segment groups for all the child outlets
  2467. ApplyRedirects.prototype.expandChildren = function (ngModule, routes, segmentGroup) {
  2468. var _this = this;
  2469. return waitForMap(segmentGroup.children, function (childOutlet, child) { return _this.expandSegmentGroup(ngModule, routes, child, childOutlet); });
  2470. };
  2471. ApplyRedirects.prototype.expandSegment = function (ngModule, segmentGroup, routes, segments, outlet, allowRedirects) {
  2472. var _this = this;
  2473. return of.apply(void 0, __spread(routes)).pipe(map(function (r) {
  2474. var expanded$ = _this.expandSegmentAgainstRoute(ngModule, segmentGroup, routes, r, segments, outlet, allowRedirects);
  2475. return expanded$.pipe(catchError(function (e) {
  2476. if (e instanceof NoMatch) {
  2477. // TODO(i): this return type doesn't match the declared Observable<UrlSegmentGroup> -
  2478. // talk to Jason
  2479. return of(null);
  2480. }
  2481. throw e;
  2482. }));
  2483. }), concatAll(), first(function (s) { return !!s; }), catchError(function (e, _) {
  2484. if (e instanceof EmptyError || e.name === 'EmptyError') {
  2485. if (_this.noLeftoversInUrl(segmentGroup, segments, outlet)) {
  2486. return of(new UrlSegmentGroup([], {}));
  2487. }
  2488. throw new NoMatch(segmentGroup);
  2489. }
  2490. throw e;
  2491. }));
  2492. };
  2493. ApplyRedirects.prototype.noLeftoversInUrl = function (segmentGroup, segments, outlet) {
  2494. return segments.length === 0 && !segmentGroup.children[outlet];
  2495. };
  2496. ApplyRedirects.prototype.expandSegmentAgainstRoute = function (ngModule, segmentGroup, routes, route, paths, outlet, allowRedirects) {
  2497. if (getOutlet(route) !== outlet) {
  2498. return noMatch(segmentGroup);
  2499. }
  2500. if (route.redirectTo === undefined) {
  2501. return this.matchSegmentAgainstRoute(ngModule, segmentGroup, route, paths);
  2502. }
  2503. if (allowRedirects && this.allowRedirects) {
  2504. return this.expandSegmentAgainstRouteUsingRedirect(ngModule, segmentGroup, routes, route, paths, outlet);
  2505. }
  2506. return noMatch(segmentGroup);
  2507. };
  2508. ApplyRedirects.prototype.expandSegmentAgainstRouteUsingRedirect = function (ngModule, segmentGroup, routes, route, segments, outlet) {
  2509. if (route.path === '**') {
  2510. return this.expandWildCardWithParamsAgainstRouteUsingRedirect(ngModule, routes, route, outlet);
  2511. }
  2512. return this.expandRegularSegmentAgainstRouteUsingRedirect(ngModule, segmentGroup, routes, route, segments, outlet);
  2513. };
  2514. ApplyRedirects.prototype.expandWildCardWithParamsAgainstRouteUsingRedirect = function (ngModule, routes, route, outlet) {
  2515. var _this = this;
  2516. var newTree = this.applyRedirectCommands([], route.redirectTo, {});
  2517. if (route.redirectTo.startsWith('/')) {
  2518. return absoluteRedirect(newTree);
  2519. }
  2520. return this.lineralizeSegments(route, newTree).pipe(mergeMap(function (newSegments) {
  2521. var group = new UrlSegmentGroup(newSegments, {});
  2522. return _this.expandSegment(ngModule, group, routes, newSegments, outlet, false);
  2523. }));
  2524. };
  2525. ApplyRedirects.prototype.expandRegularSegmentAgainstRouteUsingRedirect = function (ngModule, segmentGroup, routes, route, segments, outlet) {
  2526. var _this = this;
  2527. var _a = match(segmentGroup, route, segments), matched = _a.matched, consumedSegments = _a.consumedSegments, lastChild = _a.lastChild, positionalParamSegments = _a.positionalParamSegments;
  2528. if (!matched)
  2529. return noMatch(segmentGroup);
  2530. var newTree = this.applyRedirectCommands(consumedSegments, route.redirectTo, positionalParamSegments);
  2531. if (route.redirectTo.startsWith('/')) {
  2532. return absoluteRedirect(newTree);
  2533. }
  2534. return this.lineralizeSegments(route, newTree).pipe(mergeMap(function (newSegments) {
  2535. return _this.expandSegment(ngModule, segmentGroup, routes, newSegments.concat(segments.slice(lastChild)), outlet, false);
  2536. }));
  2537. };
  2538. ApplyRedirects.prototype.matchSegmentAgainstRoute = function (ngModule, rawSegmentGroup, route, segments) {
  2539. var _this = this;
  2540. if (route.path === '**') {
  2541. if (route.loadChildren) {
  2542. return this.configLoader.load(ngModule.injector, route)
  2543. .pipe(map(function (cfg) {
  2544. route._loadedConfig = cfg;
  2545. return new UrlSegmentGroup(segments, {});
  2546. }));
  2547. }
  2548. return of(new UrlSegmentGroup(segments, {}));
  2549. }
  2550. var _a = match(rawSegmentGroup, route, segments), matched = _a.matched, consumedSegments = _a.consumedSegments, lastChild = _a.lastChild;
  2551. if (!matched)
  2552. return noMatch(rawSegmentGroup);
  2553. var rawSlicedSegments = segments.slice(lastChild);
  2554. var childConfig$ = this.getChildConfig(ngModule, route, segments);
  2555. return childConfig$.pipe(mergeMap(function (routerConfig) {
  2556. var childModule = routerConfig.module;
  2557. var childConfig = routerConfig.routes;
  2558. var _a = split(rawSegmentGroup, consumedSegments, rawSlicedSegments, childConfig), segmentGroup = _a.segmentGroup, slicedSegments = _a.slicedSegments;
  2559. if (slicedSegments.length === 0 && segmentGroup.hasChildren()) {
  2560. var expanded$_1 = _this.expandChildren(childModule, childConfig, segmentGroup);
  2561. return expanded$_1.pipe(map(function (children) { return new UrlSegmentGroup(consumedSegments, children); }));
  2562. }
  2563. if (childConfig.length === 0 && slicedSegments.length === 0) {
  2564. return of(new UrlSegmentGroup(consumedSegments, {}));
  2565. }
  2566. var expanded$ = _this.expandSegment(childModule, segmentGroup, childConfig, slicedSegments, PRIMARY_OUTLET, true);
  2567. return expanded$.pipe(map(function (cs) {
  2568. return new UrlSegmentGroup(consumedSegments.concat(cs.segments), cs.children);
  2569. }));
  2570. }));
  2571. };
  2572. ApplyRedirects.prototype.getChildConfig = function (ngModule, route, segments) {
  2573. var _this = this;
  2574. if (route.children) {
  2575. // The children belong to the same module
  2576. return of(new LoadedRouterConfig(route.children, ngModule));
  2577. }
  2578. if (route.loadChildren) {
  2579. // lazy children belong to the loaded module
  2580. if (route._loadedConfig !== undefined) {
  2581. return of(route._loadedConfig);
  2582. }
  2583. return runCanLoadGuard(ngModule.injector, route, segments)
  2584. .pipe(mergeMap(function (shouldLoad) {
  2585. if (shouldLoad) {
  2586. return _this.configLoader.load(ngModule.injector, route)
  2587. .pipe(map(function (cfg) {
  2588. route._loadedConfig = cfg;
  2589. return cfg;
  2590. }));
  2591. }
  2592. return canLoadFails(route);
  2593. }));
  2594. }
  2595. return of(new LoadedRouterConfig([], ngModule));
  2596. };
  2597. ApplyRedirects.prototype.lineralizeSegments = function (route, urlTree) {
  2598. var res = [];
  2599. var c = urlTree.root;
  2600. while (true) {
  2601. res = res.concat(c.segments);
  2602. if (c.numberOfChildren === 0) {
  2603. return of(res);
  2604. }
  2605. if (c.numberOfChildren > 1 || !c.children[PRIMARY_OUTLET]) {
  2606. return namedOutletsRedirect(route.redirectTo);
  2607. }
  2608. c = c.children[PRIMARY_OUTLET];
  2609. }
  2610. };
  2611. ApplyRedirects.prototype.applyRedirectCommands = function (segments, redirectTo, posParams) {
  2612. return this.applyRedirectCreatreUrlTree(redirectTo, this.urlSerializer.parse(redirectTo), segments, posParams);
  2613. };
  2614. ApplyRedirects.prototype.applyRedirectCreatreUrlTree = function (redirectTo, urlTree, segments, posParams) {
  2615. var newRoot = this.createSegmentGroup(redirectTo, urlTree.root, segments, posParams);
  2616. return new UrlTree(newRoot, this.createQueryParams(urlTree.queryParams, this.urlTree.queryParams), urlTree.fragment);
  2617. };
  2618. ApplyRedirects.prototype.createQueryParams = function (redirectToParams, actualParams) {
  2619. var res = {};
  2620. forEach(redirectToParams, function (v, k) {
  2621. var copySourceValue = typeof v === 'string' && v.startsWith(':');
  2622. if (copySourceValue) {
  2623. var sourceName = v.substring(1);
  2624. res[k] = actualParams[sourceName];
  2625. }
  2626. else {
  2627. res[k] = v;
  2628. }
  2629. });
  2630. return res;
  2631. };
  2632. ApplyRedirects.prototype.createSegmentGroup = function (redirectTo, group, segments, posParams) {
  2633. var _this = this;
  2634. var updatedSegments = this.createSegments(redirectTo, group.segments, segments, posParams);
  2635. var children = {};
  2636. forEach(group.children, function (child, name) {
  2637. children[name] = _this.createSegmentGroup(redirectTo, child, segments, posParams);
  2638. });
  2639. return new UrlSegmentGroup(updatedSegments, children);
  2640. };
  2641. ApplyRedirects.prototype.createSegments = function (redirectTo, redirectToSegments, actualSegments, posParams) {
  2642. var _this = this;
  2643. return redirectToSegments.map(function (s) { return s.path.startsWith(':') ? _this.findPosParam(redirectTo, s, posParams) :
  2644. _this.findOrReturn(s, actualSegments); });
  2645. };
  2646. ApplyRedirects.prototype.findPosParam = function (redirectTo, redirectToUrlSegment, posParams) {
  2647. var pos = posParams[redirectToUrlSegment.path.substring(1)];
  2648. if (!pos)
  2649. throw new Error("Cannot redirect to '" + redirectTo + "'. Cannot find '" + redirectToUrlSegment.path + "'.");
  2650. return pos;
  2651. };
  2652. ApplyRedirects.prototype.findOrReturn = function (redirectToUrlSegment, actualSegments) {
  2653. var e_1, _a;
  2654. var idx = 0;
  2655. try {
  2656. for (var actualSegments_1 = __values(actualSegments), actualSegments_1_1 = actualSegments_1.next(); !actualSegments_1_1.done; actualSegments_1_1 = actualSegments_1.next()) {
  2657. var s = actualSegments_1_1.value;
  2658. if (s.path === redirectToUrlSegment.path) {
  2659. actualSegments.splice(idx);
  2660. return s;
  2661. }
  2662. idx++;
  2663. }
  2664. }
  2665. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  2666. finally {
  2667. try {
  2668. if (actualSegments_1_1 && !actualSegments_1_1.done && (_a = actualSegments_1.return)) _a.call(actualSegments_1);
  2669. }
  2670. finally { if (e_1) throw e_1.error; }
  2671. }
  2672. return redirectToUrlSegment;
  2673. };
  2674. return ApplyRedirects;
  2675. }());
  2676. function runCanLoadGuard(moduleInjector, route, segments) {
  2677. var canLoad = route.canLoad;
  2678. if (!canLoad || canLoad.length === 0)
  2679. return of(true);
  2680. var obs = from(canLoad).pipe(map(function (injectionToken) {
  2681. var guard = moduleInjector.get(injectionToken);
  2682. var guardVal;
  2683. if (isCanLoad(guard)) {
  2684. guardVal = guard.canLoad(route, segments);
  2685. }
  2686. else if (isFunction(guard)) {
  2687. guardVal = guard(route, segments);
  2688. }
  2689. else {
  2690. throw new Error('Invalid CanLoad guard');
  2691. }
  2692. return wrapIntoObservable(guardVal);
  2693. }));
  2694. return obs.pipe(concatAll(), every(function (result) { return result === true; }));
  2695. }
  2696. function match(segmentGroup, route, segments) {
  2697. if (route.path === '') {
  2698. if ((route.pathMatch === 'full') && (segmentGroup.hasChildren() || segments.length > 0)) {
  2699. return { matched: false, consumedSegments: [], lastChild: 0, positionalParamSegments: {} };
  2700. }
  2701. return { matched: true, consumedSegments: [], lastChild: 0, positionalParamSegments: {} };
  2702. }
  2703. var matcher = route.matcher || defaultUrlMatcher;
  2704. var res = matcher(segments, segmentGroup, route);
  2705. if (!res) {
  2706. return {
  2707. matched: false,
  2708. consumedSegments: [],
  2709. lastChild: 0,
  2710. positionalParamSegments: {},
  2711. };
  2712. }
  2713. return {
  2714. matched: true,
  2715. consumedSegments: res.consumed,
  2716. lastChild: res.consumed.length,
  2717. positionalParamSegments: res.posParams,
  2718. };
  2719. }
  2720. function split(segmentGroup, consumedSegments, slicedSegments, config) {
  2721. if (slicedSegments.length > 0 &&
  2722. containsEmptyPathRedirectsWithNamedOutlets(segmentGroup, slicedSegments, config)) {
  2723. var s = new UrlSegmentGroup(consumedSegments, createChildrenForEmptySegments(config, new UrlSegmentGroup(slicedSegments, segmentGroup.children)));
  2724. return { segmentGroup: mergeTrivialChildren(s), slicedSegments: [] };
  2725. }
  2726. if (slicedSegments.length === 0 &&
  2727. containsEmptyPathRedirects(segmentGroup, slicedSegments, config)) {
  2728. var s = new UrlSegmentGroup(segmentGroup.segments, addEmptySegmentsToChildrenIfNeeded(segmentGroup, slicedSegments, config, segmentGroup.children));
  2729. return { segmentGroup: mergeTrivialChildren(s), slicedSegments: slicedSegments };
  2730. }
  2731. return { segmentGroup: segmentGroup, slicedSegments: slicedSegments };
  2732. }
  2733. function mergeTrivialChildren(s) {
  2734. if (s.numberOfChildren === 1 && s.children[PRIMARY_OUTLET]) {
  2735. var c = s.children[PRIMARY_OUTLET];
  2736. return new UrlSegmentGroup(s.segments.concat(c.segments), c.children);
  2737. }
  2738. return s;
  2739. }
  2740. function addEmptySegmentsToChildrenIfNeeded(segmentGroup, slicedSegments, routes, children) {
  2741. var e_2, _a;
  2742. var res = {};
  2743. try {
  2744. for (var routes_1 = __values(routes), routes_1_1 = routes_1.next(); !routes_1_1.done; routes_1_1 = routes_1.next()) {
  2745. var r = routes_1_1.value;
  2746. if (isEmptyPathRedirect(segmentGroup, slicedSegments, r) && !children[getOutlet(r)]) {
  2747. res[getOutlet(r)] = new UrlSegmentGroup([], {});
  2748. }
  2749. }
  2750. }
  2751. catch (e_2_1) { e_2 = { error: e_2_1 }; }
  2752. finally {
  2753. try {
  2754. if (routes_1_1 && !routes_1_1.done && (_a = routes_1.return)) _a.call(routes_1);
  2755. }
  2756. finally { if (e_2) throw e_2.error; }
  2757. }
  2758. return __assign({}, children, res);
  2759. }
  2760. function createChildrenForEmptySegments(routes, primarySegmentGroup) {
  2761. var e_3, _a;
  2762. var res = {};
  2763. res[PRIMARY_OUTLET] = primarySegmentGroup;
  2764. try {
  2765. for (var routes_2 = __values(routes), routes_2_1 = routes_2.next(); !routes_2_1.done; routes_2_1 = routes_2.next()) {
  2766. var r = routes_2_1.value;
  2767. if (r.path === '' && getOutlet(r) !== PRIMARY_OUTLET) {
  2768. res[getOutlet(r)] = new UrlSegmentGroup([], {});
  2769. }
  2770. }
  2771. }
  2772. catch (e_3_1) { e_3 = { error: e_3_1 }; }
  2773. finally {
  2774. try {
  2775. if (routes_2_1 && !routes_2_1.done && (_a = routes_2.return)) _a.call(routes_2);
  2776. }
  2777. finally { if (e_3) throw e_3.error; }
  2778. }
  2779. return res;
  2780. }
  2781. function containsEmptyPathRedirectsWithNamedOutlets(segmentGroup, segments, routes) {
  2782. return routes.some(function (r) { return isEmptyPathRedirect(segmentGroup, segments, r) && getOutlet(r) !== PRIMARY_OUTLET; });
  2783. }
  2784. function containsEmptyPathRedirects(segmentGroup, segments, routes) {
  2785. return routes.some(function (r) { return isEmptyPathRedirect(segmentGroup, segments, r); });
  2786. }
  2787. function isEmptyPathRedirect(segmentGroup, segments, r) {
  2788. if ((segmentGroup.hasChildren() || segments.length > 0) && r.pathMatch === 'full') {
  2789. return false;
  2790. }
  2791. return r.path === '' && r.redirectTo !== undefined;
  2792. }
  2793. function getOutlet(route) {
  2794. return route.outlet || PRIMARY_OUTLET;
  2795. }
  2796. /**
  2797. * @license
  2798. * Copyright Google Inc. All Rights Reserved.
  2799. *
  2800. * Use of this source code is governed by an MIT-style license that can be
  2801. * found in the LICENSE file at https://angular.io/license
  2802. */
  2803. function applyRedirects$1(moduleInjector, configLoader, urlSerializer, config) {
  2804. return function (source) {
  2805. return source.pipe(switchMap(function (t) { return applyRedirects(moduleInjector, configLoader, urlSerializer, t.extractedUrl, config)
  2806. .pipe(map(function (urlAfterRedirects) { return (__assign({}, t, { urlAfterRedirects: urlAfterRedirects })); })); }));
  2807. };
  2808. }
  2809. /**
  2810. * @license
  2811. * Copyright Google Inc. All Rights Reserved.
  2812. *
  2813. * Use of this source code is governed by an MIT-style license that can be
  2814. * found in the LICENSE file at https://angular.io/license
  2815. */
  2816. var CanActivate = /** @class */ (function () {
  2817. function CanActivate(path) {
  2818. this.path = path;
  2819. this.route = this.path[this.path.length - 1];
  2820. }
  2821. return CanActivate;
  2822. }());
  2823. var CanDeactivate = /** @class */ (function () {
  2824. function CanDeactivate(component, route) {
  2825. this.component = component;
  2826. this.route = route;
  2827. }
  2828. return CanDeactivate;
  2829. }());
  2830. function getAllRouteGuards(future, curr, parentContexts) {
  2831. var futureRoot = future._root;
  2832. var currRoot = curr ? curr._root : null;
  2833. return getChildRouteGuards(futureRoot, currRoot, parentContexts, [futureRoot.value]);
  2834. }
  2835. function getCanActivateChild(p) {
  2836. var canActivateChild = p.routeConfig ? p.routeConfig.canActivateChild : null;
  2837. if (!canActivateChild || canActivateChild.length === 0)
  2838. return null;
  2839. return { node: p, guards: canActivateChild };
  2840. }
  2841. function getToken(token, snapshot, moduleInjector) {
  2842. var config = getClosestLoadedConfig(snapshot);
  2843. var injector = config ? config.module.injector : moduleInjector;
  2844. return injector.get(token);
  2845. }
  2846. function getClosestLoadedConfig(snapshot) {
  2847. if (!snapshot)
  2848. return null;
  2849. for (var s = snapshot.parent; s; s = s.parent) {
  2850. var route = s.routeConfig;
  2851. if (route && route._loadedConfig)
  2852. return route._loadedConfig;
  2853. }
  2854. return null;
  2855. }
  2856. function getChildRouteGuards(futureNode, currNode, contexts, futurePath, checks) {
  2857. if (checks === void 0) { checks = {
  2858. canDeactivateChecks: [],
  2859. canActivateChecks: []
  2860. }; }
  2861. var prevChildren = nodeChildrenAsMap(currNode);
  2862. // Process the children of the future route
  2863. futureNode.children.forEach(function (c) {
  2864. getRouteGuards(c, prevChildren[c.value.outlet], contexts, futurePath.concat([c.value]), checks);
  2865. delete prevChildren[c.value.outlet];
  2866. });
  2867. // Process any children left from the current route (not active for the future route)
  2868. forEach(prevChildren, function (v, k) {
  2869. return deactivateRouteAndItsChildren(v, contexts.getContext(k), checks);
  2870. });
  2871. return checks;
  2872. }
  2873. function getRouteGuards(futureNode, currNode, parentContexts, futurePath, checks) {
  2874. if (checks === void 0) { checks = {
  2875. canDeactivateChecks: [],
  2876. canActivateChecks: []
  2877. }; }
  2878. var future = futureNode.value;
  2879. var curr = currNode ? currNode.value : null;
  2880. var context = parentContexts ? parentContexts.getContext(futureNode.value.outlet) : null;
  2881. // reusing the node
  2882. if (curr && future.routeConfig === curr.routeConfig) {
  2883. var shouldRun = shouldRunGuardsAndResolvers(curr, future, future.routeConfig.runGuardsAndResolvers);
  2884. if (shouldRun) {
  2885. checks.canActivateChecks.push(new CanActivate(futurePath));
  2886. }
  2887. else {
  2888. // we need to set the data
  2889. future.data = curr.data;
  2890. future._resolvedData = curr._resolvedData;
  2891. }
  2892. // If we have a component, we need to go through an outlet.
  2893. if (future.component) {
  2894. getChildRouteGuards(futureNode, currNode, context ? context.children : null, futurePath, checks);
  2895. // if we have a componentless route, we recurse but keep the same outlet map.
  2896. }
  2897. else {
  2898. getChildRouteGuards(futureNode, currNode, parentContexts, futurePath, checks);
  2899. }
  2900. if (shouldRun) {
  2901. var component = context && context.outlet && context.outlet.component || null;
  2902. checks.canDeactivateChecks.push(new CanDeactivate(component, curr));
  2903. }
  2904. }
  2905. else {
  2906. if (curr) {
  2907. deactivateRouteAndItsChildren(currNode, context, checks);
  2908. }
  2909. checks.canActivateChecks.push(new CanActivate(futurePath));
  2910. // If we have a component, we need to go through an outlet.
  2911. if (future.component) {
  2912. getChildRouteGuards(futureNode, null, context ? context.children : null, futurePath, checks);
  2913. // if we have a componentless route, we recurse but keep the same outlet map.
  2914. }
  2915. else {
  2916. getChildRouteGuards(futureNode, null, parentContexts, futurePath, checks);
  2917. }
  2918. }
  2919. return checks;
  2920. }
  2921. function shouldRunGuardsAndResolvers(curr, future, mode) {
  2922. if (typeof mode === 'function') {
  2923. return mode(curr, future);
  2924. }
  2925. switch (mode) {
  2926. case 'pathParamsChange':
  2927. return !equalPath(curr.url, future.url);
  2928. case 'pathParamsOrQueryParamsChange':
  2929. return !equalPath(curr.url, future.url) ||
  2930. !shallowEqual(curr.queryParams, future.queryParams);
  2931. case 'always':
  2932. return true;
  2933. case 'paramsOrQueryParamsChange':
  2934. return !equalParamsAndUrlSegments(curr, future) ||
  2935. !shallowEqual(curr.queryParams, future.queryParams);
  2936. case 'paramsChange':
  2937. default:
  2938. return !equalParamsAndUrlSegments(curr, future);
  2939. }
  2940. }
  2941. function deactivateRouteAndItsChildren(route, context, checks) {
  2942. var children = nodeChildrenAsMap(route);
  2943. var r = route.value;
  2944. forEach(children, function (node, childName) {
  2945. if (!r.component) {
  2946. deactivateRouteAndItsChildren(node, context, checks);
  2947. }
  2948. else if (context) {
  2949. deactivateRouteAndItsChildren(node, context.children.getContext(childName), checks);
  2950. }
  2951. else {
  2952. deactivateRouteAndItsChildren(node, null, checks);
  2953. }
  2954. });
  2955. if (!r.component) {
  2956. checks.canDeactivateChecks.push(new CanDeactivate(null, r));
  2957. }
  2958. else if (context && context.outlet && context.outlet.isActivated) {
  2959. checks.canDeactivateChecks.push(new CanDeactivate(context.outlet.component, r));
  2960. }
  2961. else {
  2962. checks.canDeactivateChecks.push(new CanDeactivate(null, r));
  2963. }
  2964. }
  2965. /**
  2966. * @license
  2967. * Copyright Google Inc. All Rights Reserved.
  2968. *
  2969. * Use of this source code is governed by an MIT-style license that can be
  2970. * found in the LICENSE file at https://angular.io/license
  2971. */
  2972. var INITIAL_VALUE = Symbol('INITIAL_VALUE');
  2973. function prioritizedGuardValue() {
  2974. return switchMap(function (obs) {
  2975. return combineLatest.apply(void 0, __spread(obs.map(function (o) { return o.pipe(take(1), startWith(INITIAL_VALUE)); }))).pipe(scan(function (acc, list) {
  2976. var isPending = false;
  2977. return list.reduce(function (innerAcc, val, i) {
  2978. if (innerAcc !== INITIAL_VALUE)
  2979. return innerAcc;
  2980. // Toggle pending flag if any values haven't been set yet
  2981. if (val === INITIAL_VALUE)
  2982. isPending = true;
  2983. // Any other return values are only valid if we haven't yet hit a pending call.
  2984. // This guarantees that in the case of a guard at the bottom of the tree that
  2985. // returns a redirect, we will wait for the higher priority guard at the top to
  2986. // finish before performing the redirect.
  2987. if (!isPending) {
  2988. // Early return when we hit a `false` value as that should always cancel
  2989. // navigation
  2990. if (val === false)
  2991. return val;
  2992. if (i === list.length - 1 || isUrlTree(val)) {
  2993. return val;
  2994. }
  2995. }
  2996. return innerAcc;
  2997. }, acc);
  2998. }, INITIAL_VALUE), filter(function (item) { return item !== INITIAL_VALUE; }), map(function (item) { return isUrlTree(item) ? item : item === true; }), //
  2999. take(1));
  3000. });
  3001. }
  3002. /**
  3003. * @license
  3004. * Copyright Google Inc. All Rights Reserved.
  3005. *
  3006. * Use of this source code is governed by an MIT-style license that can be
  3007. * found in the LICENSE file at https://angular.io/license
  3008. */
  3009. function checkGuards(moduleInjector, forwardEvent) {
  3010. return function (source) {
  3011. return source.pipe(mergeMap(function (t) {
  3012. var targetSnapshot = t.targetSnapshot, currentSnapshot = t.currentSnapshot, _a = t.guards, canActivateChecks = _a.canActivateChecks, canDeactivateChecks = _a.canDeactivateChecks;
  3013. if (canDeactivateChecks.length === 0 && canActivateChecks.length === 0) {
  3014. return of(__assign({}, t, { guardsResult: true }));
  3015. }
  3016. return runCanDeactivateChecks(canDeactivateChecks, targetSnapshot, currentSnapshot, moduleInjector)
  3017. .pipe(mergeMap(function (canDeactivate) {
  3018. return canDeactivate && isBoolean(canDeactivate) ?
  3019. runCanActivateChecks(targetSnapshot, canActivateChecks, moduleInjector, forwardEvent) :
  3020. of(canDeactivate);
  3021. }), map(function (guardsResult) { return (__assign({}, t, { guardsResult: guardsResult })); }));
  3022. }));
  3023. };
  3024. }
  3025. function runCanDeactivateChecks(checks, futureRSS, currRSS, moduleInjector) {
  3026. return from(checks).pipe(mergeMap(function (check) {
  3027. return runCanDeactivate(check.component, check.route, currRSS, futureRSS, moduleInjector);
  3028. }), first(function (result) { return result !== true; }, true));
  3029. }
  3030. function runCanActivateChecks(futureSnapshot, checks, moduleInjector, forwardEvent) {
  3031. return from(checks).pipe(concatMap(function (check) {
  3032. return from([
  3033. fireChildActivationStart(check.route.parent, forwardEvent),
  3034. fireActivationStart(check.route, forwardEvent),
  3035. runCanActivateChild(futureSnapshot, check.path, moduleInjector),
  3036. runCanActivate(futureSnapshot, check.route, moduleInjector)
  3037. ])
  3038. .pipe(concatAll(), first(function (result) {
  3039. return result !== true;
  3040. }, true));
  3041. }), first(function (result) { return result !== true; }, true));
  3042. }
  3043. /**
  3044. * This should fire off `ActivationStart` events for each route being activated at this
  3045. * level.
  3046. * In other words, if you're activating `a` and `b` below, `path` will contain the
  3047. * `ActivatedRouteSnapshot`s for both and we will fire `ActivationStart` for both. Always
  3048. * return
  3049. * `true` so checks continue to run.
  3050. */
  3051. function fireActivationStart(snapshot, forwardEvent) {
  3052. if (snapshot !== null && forwardEvent) {
  3053. forwardEvent(new ActivationStart(snapshot));
  3054. }
  3055. return of(true);
  3056. }
  3057. /**
  3058. * This should fire off `ChildActivationStart` events for each route being activated at this
  3059. * level.
  3060. * In other words, if you're activating `a` and `b` below, `path` will contain the
  3061. * `ActivatedRouteSnapshot`s for both and we will fire `ChildActivationStart` for both. Always
  3062. * return
  3063. * `true` so checks continue to run.
  3064. */
  3065. function fireChildActivationStart(snapshot, forwardEvent) {
  3066. if (snapshot !== null && forwardEvent) {
  3067. forwardEvent(new ChildActivationStart(snapshot));
  3068. }
  3069. return of(true);
  3070. }
  3071. function runCanActivate(futureRSS, futureARS, moduleInjector) {
  3072. var canActivate = futureARS.routeConfig ? futureARS.routeConfig.canActivate : null;
  3073. if (!canActivate || canActivate.length === 0)
  3074. return of(true);
  3075. var canActivateObservables = canActivate.map(function (c) {
  3076. return defer(function () {
  3077. var guard = getToken(c, futureARS, moduleInjector);
  3078. var observable;
  3079. if (isCanActivate(guard)) {
  3080. observable = wrapIntoObservable(guard.canActivate(futureARS, futureRSS));
  3081. }
  3082. else if (isFunction(guard)) {
  3083. observable = wrapIntoObservable(guard(futureARS, futureRSS));
  3084. }
  3085. else {
  3086. throw new Error('Invalid CanActivate guard');
  3087. }
  3088. return observable.pipe(first());
  3089. });
  3090. });
  3091. return of(canActivateObservables).pipe(prioritizedGuardValue());
  3092. }
  3093. function runCanActivateChild(futureRSS, path, moduleInjector) {
  3094. var futureARS = path[path.length - 1];
  3095. var canActivateChildGuards = path.slice(0, path.length - 1)
  3096. .reverse()
  3097. .map(function (p) { return getCanActivateChild(p); })
  3098. .filter(function (_) { return _ !== null; });
  3099. var canActivateChildGuardsMapped = canActivateChildGuards.map(function (d) {
  3100. return defer(function () {
  3101. var guardsMapped = d.guards.map(function (c) {
  3102. var guard = getToken(c, d.node, moduleInjector);
  3103. var observable;
  3104. if (isCanActivateChild(guard)) {
  3105. observable = wrapIntoObservable(guard.canActivateChild(futureARS, futureRSS));
  3106. }
  3107. else if (isFunction(guard)) {
  3108. observable = wrapIntoObservable(guard(futureARS, futureRSS));
  3109. }
  3110. else {
  3111. throw new Error('Invalid CanActivateChild guard');
  3112. }
  3113. return observable.pipe(first());
  3114. });
  3115. return of(guardsMapped).pipe(prioritizedGuardValue());
  3116. });
  3117. });
  3118. return of(canActivateChildGuardsMapped).pipe(prioritizedGuardValue());
  3119. }
  3120. function runCanDeactivate(component, currARS, currRSS, futureRSS, moduleInjector) {
  3121. var canDeactivate = currARS && currARS.routeConfig ? currARS.routeConfig.canDeactivate : null;
  3122. if (!canDeactivate || canDeactivate.length === 0)
  3123. return of(true);
  3124. var canDeactivateObservables = canDeactivate.map(function (c) {
  3125. var guard = getToken(c, currARS, moduleInjector);
  3126. var observable;
  3127. if (isCanDeactivate(guard)) {
  3128. observable =
  3129. wrapIntoObservable(guard.canDeactivate(component, currARS, currRSS, futureRSS));
  3130. }
  3131. else if (isFunction(guard)) {
  3132. observable = wrapIntoObservable(guard(component, currARS, currRSS, futureRSS));
  3133. }
  3134. else {
  3135. throw new Error('Invalid CanDeactivate guard');
  3136. }
  3137. return observable.pipe(first());
  3138. });
  3139. return of(canDeactivateObservables).pipe(prioritizedGuardValue());
  3140. }
  3141. /**
  3142. * @license
  3143. * Copyright Google Inc. All Rights Reserved.
  3144. *
  3145. * Use of this source code is governed by an MIT-style license that can be
  3146. * found in the LICENSE file at https://angular.io/license
  3147. */
  3148. var NoMatch$1 = /** @class */ (function () {
  3149. function NoMatch() {
  3150. }
  3151. return NoMatch;
  3152. }());
  3153. function recognize(rootComponentType, config, urlTree, url, paramsInheritanceStrategy, relativeLinkResolution) {
  3154. if (paramsInheritanceStrategy === void 0) { paramsInheritanceStrategy = 'emptyOnly'; }
  3155. if (relativeLinkResolution === void 0) { relativeLinkResolution = 'legacy'; }
  3156. return new Recognizer(rootComponentType, config, urlTree, url, paramsInheritanceStrategy, relativeLinkResolution)
  3157. .recognize();
  3158. }
  3159. var Recognizer = /** @class */ (function () {
  3160. function Recognizer(rootComponentType, config, urlTree, url, paramsInheritanceStrategy, relativeLinkResolution) {
  3161. this.rootComponentType = rootComponentType;
  3162. this.config = config;
  3163. this.urlTree = urlTree;
  3164. this.url = url;
  3165. this.paramsInheritanceStrategy = paramsInheritanceStrategy;
  3166. this.relativeLinkResolution = relativeLinkResolution;
  3167. }
  3168. Recognizer.prototype.recognize = function () {
  3169. try {
  3170. var rootSegmentGroup = split$1(this.urlTree.root, [], [], this.config, this.relativeLinkResolution).segmentGroup;
  3171. var children = this.processSegmentGroup(this.config, rootSegmentGroup, PRIMARY_OUTLET);
  3172. var root = new ActivatedRouteSnapshot([], Object.freeze({}), Object.freeze(__assign({}, this.urlTree.queryParams)), this.urlTree.fragment, {}, PRIMARY_OUTLET, this.rootComponentType, null, this.urlTree.root, -1, {});
  3173. var rootNode = new TreeNode(root, children);
  3174. var routeState = new RouterStateSnapshot(this.url, rootNode);
  3175. this.inheritParamsAndData(routeState._root);
  3176. return of(routeState);
  3177. }
  3178. catch (e) {
  3179. return new Observable(function (obs) { return obs.error(e); });
  3180. }
  3181. };
  3182. Recognizer.prototype.inheritParamsAndData = function (routeNode) {
  3183. var _this = this;
  3184. var route = routeNode.value;
  3185. var i = inheritedParamsDataResolve(route, this.paramsInheritanceStrategy);
  3186. route.params = Object.freeze(i.params);
  3187. route.data = Object.freeze(i.data);
  3188. routeNode.children.forEach(function (n) { return _this.inheritParamsAndData(n); });
  3189. };
  3190. Recognizer.prototype.processSegmentGroup = function (config, segmentGroup, outlet) {
  3191. if (segmentGroup.segments.length === 0 && segmentGroup.hasChildren()) {
  3192. return this.processChildren(config, segmentGroup);
  3193. }
  3194. return this.processSegment(config, segmentGroup, segmentGroup.segments, outlet);
  3195. };
  3196. Recognizer.prototype.processChildren = function (config, segmentGroup) {
  3197. var _this = this;
  3198. var children = mapChildrenIntoArray(segmentGroup, function (child, childOutlet) { return _this.processSegmentGroup(config, child, childOutlet); });
  3199. checkOutletNameUniqueness(children);
  3200. sortActivatedRouteSnapshots(children);
  3201. return children;
  3202. };
  3203. Recognizer.prototype.processSegment = function (config, segmentGroup, segments, outlet) {
  3204. var e_1, _a;
  3205. try {
  3206. for (var config_1 = __values(config), config_1_1 = config_1.next(); !config_1_1.done; config_1_1 = config_1.next()) {
  3207. var r = config_1_1.value;
  3208. try {
  3209. return this.processSegmentAgainstRoute(r, segmentGroup, segments, outlet);
  3210. }
  3211. catch (e) {
  3212. if (!(e instanceof NoMatch$1))
  3213. throw e;
  3214. }
  3215. }
  3216. }
  3217. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  3218. finally {
  3219. try {
  3220. if (config_1_1 && !config_1_1.done && (_a = config_1.return)) _a.call(config_1);
  3221. }
  3222. finally { if (e_1) throw e_1.error; }
  3223. }
  3224. if (this.noLeftoversInUrl(segmentGroup, segments, outlet)) {
  3225. return [];
  3226. }
  3227. throw new NoMatch$1();
  3228. };
  3229. Recognizer.prototype.noLeftoversInUrl = function (segmentGroup, segments, outlet) {
  3230. return segments.length === 0 && !segmentGroup.children[outlet];
  3231. };
  3232. Recognizer.prototype.processSegmentAgainstRoute = function (route, rawSegment, segments, outlet) {
  3233. if (route.redirectTo)
  3234. throw new NoMatch$1();
  3235. if ((route.outlet || PRIMARY_OUTLET) !== outlet)
  3236. throw new NoMatch$1();
  3237. var snapshot;
  3238. var consumedSegments = [];
  3239. var rawSlicedSegments = [];
  3240. if (route.path === '**') {
  3241. var params = segments.length > 0 ? last(segments).parameters : {};
  3242. snapshot = new ActivatedRouteSnapshot(segments, params, Object.freeze(__assign({}, this.urlTree.queryParams)), this.urlTree.fragment, getData(route), outlet, route.component, route, getSourceSegmentGroup(rawSegment), getPathIndexShift(rawSegment) + segments.length, getResolve(route));
  3243. }
  3244. else {
  3245. var result = match$1(rawSegment, route, segments);
  3246. consumedSegments = result.consumedSegments;
  3247. rawSlicedSegments = segments.slice(result.lastChild);
  3248. snapshot = new ActivatedRouteSnapshot(consumedSegments, result.parameters, Object.freeze(__assign({}, this.urlTree.queryParams)), this.urlTree.fragment, getData(route), outlet, route.component, route, getSourceSegmentGroup(rawSegment), getPathIndexShift(rawSegment) + consumedSegments.length, getResolve(route));
  3249. }
  3250. var childConfig = getChildConfig(route);
  3251. var _a = split$1(rawSegment, consumedSegments, rawSlicedSegments, childConfig, this.relativeLinkResolution), segmentGroup = _a.segmentGroup, slicedSegments = _a.slicedSegments;
  3252. if (slicedSegments.length === 0 && segmentGroup.hasChildren()) {
  3253. var children_1 = this.processChildren(childConfig, segmentGroup);
  3254. return [new TreeNode(snapshot, children_1)];
  3255. }
  3256. if (childConfig.length === 0 && slicedSegments.length === 0) {
  3257. return [new TreeNode(snapshot, [])];
  3258. }
  3259. var children = this.processSegment(childConfig, segmentGroup, slicedSegments, PRIMARY_OUTLET);
  3260. return [new TreeNode(snapshot, children)];
  3261. };
  3262. return Recognizer;
  3263. }());
  3264. function sortActivatedRouteSnapshots(nodes) {
  3265. nodes.sort(function (a, b) {
  3266. if (a.value.outlet === PRIMARY_OUTLET)
  3267. return -1;
  3268. if (b.value.outlet === PRIMARY_OUTLET)
  3269. return 1;
  3270. return a.value.outlet.localeCompare(b.value.outlet);
  3271. });
  3272. }
  3273. function getChildConfig(route) {
  3274. if (route.children) {
  3275. return route.children;
  3276. }
  3277. if (route.loadChildren) {
  3278. return route._loadedConfig.routes;
  3279. }
  3280. return [];
  3281. }
  3282. function match$1(segmentGroup, route, segments) {
  3283. if (route.path === '') {
  3284. if (route.pathMatch === 'full' && (segmentGroup.hasChildren() || segments.length > 0)) {
  3285. throw new NoMatch$1();
  3286. }
  3287. return { consumedSegments: [], lastChild: 0, parameters: {} };
  3288. }
  3289. var matcher = route.matcher || defaultUrlMatcher;
  3290. var res = matcher(segments, segmentGroup, route);
  3291. if (!res)
  3292. throw new NoMatch$1();
  3293. var posParams = {};
  3294. forEach(res.posParams, function (v, k) { posParams[k] = v.path; });
  3295. var parameters = res.consumed.length > 0 ? __assign({}, posParams, res.consumed[res.consumed.length - 1].parameters) :
  3296. posParams;
  3297. return { consumedSegments: res.consumed, lastChild: res.consumed.length, parameters: parameters };
  3298. }
  3299. function checkOutletNameUniqueness(nodes) {
  3300. var names = {};
  3301. nodes.forEach(function (n) {
  3302. var routeWithSameOutletName = names[n.value.outlet];
  3303. if (routeWithSameOutletName) {
  3304. var p = routeWithSameOutletName.url.map(function (s) { return s.toString(); }).join('/');
  3305. var c = n.value.url.map(function (s) { return s.toString(); }).join('/');
  3306. throw new Error("Two segments cannot have the same outlet name: '" + p + "' and '" + c + "'.");
  3307. }
  3308. names[n.value.outlet] = n.value;
  3309. });
  3310. }
  3311. function getSourceSegmentGroup(segmentGroup) {
  3312. var s = segmentGroup;
  3313. while (s._sourceSegment) {
  3314. s = s._sourceSegment;
  3315. }
  3316. return s;
  3317. }
  3318. function getPathIndexShift(segmentGroup) {
  3319. var s = segmentGroup;
  3320. var res = (s._segmentIndexShift ? s._segmentIndexShift : 0);
  3321. while (s._sourceSegment) {
  3322. s = s._sourceSegment;
  3323. res += (s._segmentIndexShift ? s._segmentIndexShift : 0);
  3324. }
  3325. return res - 1;
  3326. }
  3327. function split$1(segmentGroup, consumedSegments, slicedSegments, config, relativeLinkResolution) {
  3328. if (slicedSegments.length > 0 &&
  3329. containsEmptyPathMatchesWithNamedOutlets(segmentGroup, slicedSegments, config)) {
  3330. var s_1 = new UrlSegmentGroup(consumedSegments, createChildrenForEmptyPaths(segmentGroup, consumedSegments, config, new UrlSegmentGroup(slicedSegments, segmentGroup.children)));
  3331. s_1._sourceSegment = segmentGroup;
  3332. s_1._segmentIndexShift = consumedSegments.length;
  3333. return { segmentGroup: s_1, slicedSegments: [] };
  3334. }
  3335. if (slicedSegments.length === 0 &&
  3336. containsEmptyPathMatches(segmentGroup, slicedSegments, config)) {
  3337. var s_2 = new UrlSegmentGroup(segmentGroup.segments, addEmptyPathsToChildrenIfNeeded(segmentGroup, consumedSegments, slicedSegments, config, segmentGroup.children, relativeLinkResolution));
  3338. s_2._sourceSegment = segmentGroup;
  3339. s_2._segmentIndexShift = consumedSegments.length;
  3340. return { segmentGroup: s_2, slicedSegments: slicedSegments };
  3341. }
  3342. var s = new UrlSegmentGroup(segmentGroup.segments, segmentGroup.children);
  3343. s._sourceSegment = segmentGroup;
  3344. s._segmentIndexShift = consumedSegments.length;
  3345. return { segmentGroup: s, slicedSegments: slicedSegments };
  3346. }
  3347. function addEmptyPathsToChildrenIfNeeded(segmentGroup, consumedSegments, slicedSegments, routes, children, relativeLinkResolution) {
  3348. var e_2, _a;
  3349. var res = {};
  3350. try {
  3351. for (var routes_1 = __values(routes), routes_1_1 = routes_1.next(); !routes_1_1.done; routes_1_1 = routes_1.next()) {
  3352. var r = routes_1_1.value;
  3353. if (emptyPathMatch(segmentGroup, slicedSegments, r) && !children[getOutlet$1(r)]) {
  3354. var s = new UrlSegmentGroup([], {});
  3355. s._sourceSegment = segmentGroup;
  3356. if (relativeLinkResolution === 'legacy') {
  3357. s._segmentIndexShift = segmentGroup.segments.length;
  3358. }
  3359. else {
  3360. s._segmentIndexShift = consumedSegments.length;
  3361. }
  3362. res[getOutlet$1(r)] = s;
  3363. }
  3364. }
  3365. }
  3366. catch (e_2_1) { e_2 = { error: e_2_1 }; }
  3367. finally {
  3368. try {
  3369. if (routes_1_1 && !routes_1_1.done && (_a = routes_1.return)) _a.call(routes_1);
  3370. }
  3371. finally { if (e_2) throw e_2.error; }
  3372. }
  3373. return __assign({}, children, res);
  3374. }
  3375. function createChildrenForEmptyPaths(segmentGroup, consumedSegments, routes, primarySegment) {
  3376. var e_3, _a;
  3377. var res = {};
  3378. res[PRIMARY_OUTLET] = primarySegment;
  3379. primarySegment._sourceSegment = segmentGroup;
  3380. primarySegment._segmentIndexShift = consumedSegments.length;
  3381. try {
  3382. for (var routes_2 = __values(routes), routes_2_1 = routes_2.next(); !routes_2_1.done; routes_2_1 = routes_2.next()) {
  3383. var r = routes_2_1.value;
  3384. if (r.path === '' && getOutlet$1(r) !== PRIMARY_OUTLET) {
  3385. var s = new UrlSegmentGroup([], {});
  3386. s._sourceSegment = segmentGroup;
  3387. s._segmentIndexShift = consumedSegments.length;
  3388. res[getOutlet$1(r)] = s;
  3389. }
  3390. }
  3391. }
  3392. catch (e_3_1) { e_3 = { error: e_3_1 }; }
  3393. finally {
  3394. try {
  3395. if (routes_2_1 && !routes_2_1.done && (_a = routes_2.return)) _a.call(routes_2);
  3396. }
  3397. finally { if (e_3) throw e_3.error; }
  3398. }
  3399. return res;
  3400. }
  3401. function containsEmptyPathMatchesWithNamedOutlets(segmentGroup, slicedSegments, routes) {
  3402. return routes.some(function (r) { return emptyPathMatch(segmentGroup, slicedSegments, r) && getOutlet$1(r) !== PRIMARY_OUTLET; });
  3403. }
  3404. function containsEmptyPathMatches(segmentGroup, slicedSegments, routes) {
  3405. return routes.some(function (r) { return emptyPathMatch(segmentGroup, slicedSegments, r); });
  3406. }
  3407. function emptyPathMatch(segmentGroup, slicedSegments, r) {
  3408. if ((segmentGroup.hasChildren() || slicedSegments.length > 0) && r.pathMatch === 'full') {
  3409. return false;
  3410. }
  3411. return r.path === '' && r.redirectTo === undefined;
  3412. }
  3413. function getOutlet$1(route) {
  3414. return route.outlet || PRIMARY_OUTLET;
  3415. }
  3416. function getData(route) {
  3417. return route.data || {};
  3418. }
  3419. function getResolve(route) {
  3420. return route.resolve || {};
  3421. }
  3422. /**
  3423. * @license
  3424. * Copyright Google Inc. All Rights Reserved.
  3425. *
  3426. * Use of this source code is governed by an MIT-style license that can be
  3427. * found in the LICENSE file at https://angular.io/license
  3428. */
  3429. function recognize$1(rootComponentType, config, serializer, paramsInheritanceStrategy, relativeLinkResolution) {
  3430. return function (source) {
  3431. return source.pipe(mergeMap(function (t) { return recognize(rootComponentType, config, t.urlAfterRedirects, serializer(t.urlAfterRedirects), paramsInheritanceStrategy, relativeLinkResolution)
  3432. .pipe(map(function (targetSnapshot) { return (__assign({}, t, { targetSnapshot: targetSnapshot })); })); }));
  3433. };
  3434. }
  3435. /**
  3436. * @license
  3437. * Copyright Google Inc. All Rights Reserved.
  3438. *
  3439. * Use of this source code is governed by an MIT-style license that can be
  3440. * found in the LICENSE file at https://angular.io/license
  3441. */
  3442. function resolveData(paramsInheritanceStrategy, moduleInjector) {
  3443. return function (source) {
  3444. return source.pipe(mergeMap(function (t) {
  3445. var targetSnapshot = t.targetSnapshot, canActivateChecks = t.guards.canActivateChecks;
  3446. if (!canActivateChecks.length) {
  3447. return of(t);
  3448. }
  3449. return from(canActivateChecks)
  3450. .pipe(concatMap(function (check) { return runResolve(check.route, targetSnapshot, paramsInheritanceStrategy, moduleInjector); }), reduce(function (_, __) { return _; }), map(function (_) { return t; }));
  3451. }));
  3452. };
  3453. }
  3454. function runResolve(futureARS, futureRSS, paramsInheritanceStrategy, moduleInjector) {
  3455. var resolve = futureARS._resolve;
  3456. return resolveNode(resolve, futureARS, futureRSS, moduleInjector)
  3457. .pipe(map(function (resolvedData) {
  3458. futureARS._resolvedData = resolvedData;
  3459. futureARS.data = __assign({}, futureARS.data, inheritedParamsDataResolve(futureARS, paramsInheritanceStrategy).resolve);
  3460. return null;
  3461. }));
  3462. }
  3463. function resolveNode(resolve, futureARS, futureRSS, moduleInjector) {
  3464. var keys = Object.keys(resolve);
  3465. if (keys.length === 0) {
  3466. return of({});
  3467. }
  3468. if (keys.length === 1) {
  3469. var key_1 = keys[0];
  3470. return getResolver(resolve[key_1], futureARS, futureRSS, moduleInjector)
  3471. .pipe(map(function (value) {
  3472. var _a;
  3473. return _a = {}, _a[key_1] = value, _a;
  3474. }));
  3475. }
  3476. var data = {};
  3477. var runningResolvers$ = from(keys).pipe(mergeMap(function (key) {
  3478. return getResolver(resolve[key], futureARS, futureRSS, moduleInjector)
  3479. .pipe(map(function (value) {
  3480. data[key] = value;
  3481. return value;
  3482. }));
  3483. }));
  3484. return runningResolvers$.pipe(last$1(), map(function () { return data; }));
  3485. }
  3486. function getResolver(injectionToken, futureARS, futureRSS, moduleInjector) {
  3487. var resolver = getToken(injectionToken, futureARS, moduleInjector);
  3488. return resolver.resolve ? wrapIntoObservable(resolver.resolve(futureARS, futureRSS)) :
  3489. wrapIntoObservable(resolver(futureARS, futureRSS));
  3490. }
  3491. /**
  3492. * @license
  3493. * Copyright Google Inc. All Rights Reserved.
  3494. *
  3495. * Use of this source code is governed by an MIT-style license that can be
  3496. * found in the LICENSE file at https://angular.io/license
  3497. */
  3498. /**
  3499. * Perform a side effect through a switchMap for every emission on the source Observable,
  3500. * but return an Observable that is identical to the source. It's essentially the same as
  3501. * the `tap` operator, but if the side effectful `next` function returns an ObservableInput,
  3502. * it will wait before continuing with the original value.
  3503. */
  3504. function switchTap(next) {
  3505. return function (source) {
  3506. return source.pipe(switchMap(function (v) {
  3507. var nextResult = next(v);
  3508. if (nextResult) {
  3509. return from(nextResult).pipe(map(function () { return v; }));
  3510. }
  3511. return from([v]);
  3512. }));
  3513. };
  3514. }
  3515. /**
  3516. * @license
  3517. * Copyright Google Inc. All Rights Reserved.
  3518. *
  3519. * Use of this source code is governed by an MIT-style license that can be
  3520. * found in the LICENSE file at https://angular.io/license
  3521. */
  3522. /**
  3523. * @description
  3524. *
  3525. * Provides a way to customize when activated routes get reused.
  3526. *
  3527. * @publicApi
  3528. */
  3529. var RouteReuseStrategy = /** @class */ (function () {
  3530. function RouteReuseStrategy() {
  3531. }
  3532. return RouteReuseStrategy;
  3533. }());
  3534. /**
  3535. * Does not detach any subtrees. Reuses routes as long as their route config is the same.
  3536. */
  3537. var DefaultRouteReuseStrategy = /** @class */ (function () {
  3538. function DefaultRouteReuseStrategy() {
  3539. }
  3540. DefaultRouteReuseStrategy.prototype.shouldDetach = function (route) { return false; };
  3541. DefaultRouteReuseStrategy.prototype.store = function (route, detachedTree) { };
  3542. DefaultRouteReuseStrategy.prototype.shouldAttach = function (route) { return false; };
  3543. DefaultRouteReuseStrategy.prototype.retrieve = function (route) { return null; };
  3544. DefaultRouteReuseStrategy.prototype.shouldReuseRoute = function (future, curr) {
  3545. return future.routeConfig === curr.routeConfig;
  3546. };
  3547. return DefaultRouteReuseStrategy;
  3548. }());
  3549. /**
  3550. * @license
  3551. * Copyright Google Inc. All Rights Reserved.
  3552. *
  3553. * Use of this source code is governed by an MIT-style license that can be
  3554. * found in the LICENSE file at https://angular.io/license
  3555. */
  3556. /**
  3557. * @docsNotRequired
  3558. * @publicApi
  3559. */
  3560. var ROUTES = new InjectionToken('ROUTES');
  3561. var RouterConfigLoader = /** @class */ (function () {
  3562. function RouterConfigLoader(loader, compiler, onLoadStartListener, onLoadEndListener) {
  3563. this.loader = loader;
  3564. this.compiler = compiler;
  3565. this.onLoadStartListener = onLoadStartListener;
  3566. this.onLoadEndListener = onLoadEndListener;
  3567. }
  3568. RouterConfigLoader.prototype.load = function (parentInjector, route) {
  3569. var _this = this;
  3570. if (this.onLoadStartListener) {
  3571. this.onLoadStartListener(route);
  3572. }
  3573. var moduleFactory$ = this.loadModuleFactory(route.loadChildren);
  3574. return moduleFactory$.pipe(map(function (factory) {
  3575. if (_this.onLoadEndListener) {
  3576. _this.onLoadEndListener(route);
  3577. }
  3578. var module = factory.create(parentInjector);
  3579. return new LoadedRouterConfig(flatten(module.injector.get(ROUTES)).map(standardizeConfig), module);
  3580. }));
  3581. };
  3582. RouterConfigLoader.prototype.loadModuleFactory = function (loadChildren) {
  3583. var _this = this;
  3584. if (typeof loadChildren === 'string') {
  3585. return from(this.loader.load(loadChildren));
  3586. }
  3587. else {
  3588. return wrapIntoObservable(loadChildren()).pipe(mergeMap(function (t) {
  3589. if (t instanceof NgModuleFactory) {
  3590. return of(t);
  3591. }
  3592. else {
  3593. return from(_this.compiler.compileModuleAsync(t));
  3594. }
  3595. }));
  3596. }
  3597. };
  3598. return RouterConfigLoader;
  3599. }());
  3600. /**
  3601. * @license
  3602. * Copyright Google Inc. All Rights Reserved.
  3603. *
  3604. * Use of this source code is governed by an MIT-style license that can be
  3605. * found in the LICENSE file at https://angular.io/license
  3606. */
  3607. /**
  3608. * @description
  3609. *
  3610. * Provides a way to migrate AngularJS applications to Angular.
  3611. *
  3612. * @publicApi
  3613. */
  3614. var UrlHandlingStrategy = /** @class */ (function () {
  3615. function UrlHandlingStrategy() {
  3616. }
  3617. return UrlHandlingStrategy;
  3618. }());
  3619. /**
  3620. * @publicApi
  3621. */
  3622. var DefaultUrlHandlingStrategy = /** @class */ (function () {
  3623. function DefaultUrlHandlingStrategy() {
  3624. }
  3625. DefaultUrlHandlingStrategy.prototype.shouldProcessUrl = function (url) { return true; };
  3626. DefaultUrlHandlingStrategy.prototype.extract = function (url) { return url; };
  3627. DefaultUrlHandlingStrategy.prototype.merge = function (newUrlPart, wholeUrl) { return newUrlPart; };
  3628. return DefaultUrlHandlingStrategy;
  3629. }());
  3630. /**
  3631. * @license
  3632. * Copyright Google Inc. All Rights Reserved.
  3633. *
  3634. * Use of this source code is governed by an MIT-style license that can be
  3635. * found in the LICENSE file at https://angular.io/license
  3636. */
  3637. function defaultErrorHandler(error) {
  3638. throw error;
  3639. }
  3640. function defaultMalformedUriErrorHandler(error, urlSerializer, url) {
  3641. return urlSerializer.parse('/');
  3642. }
  3643. /**
  3644. * @internal
  3645. */
  3646. function defaultRouterHook(snapshot, runExtras) {
  3647. return of(null);
  3648. }
  3649. /**
  3650. * @description
  3651. *
  3652. * An NgModule that provides navigation and URL manipulation capabilities.
  3653. *
  3654. * @see `Route`.
  3655. * @see [Routing and Navigation Guide](guide/router).
  3656. *
  3657. * @ngModule RouterModule
  3658. *
  3659. * @publicApi
  3660. */
  3661. var Router = /** @class */ (function () {
  3662. /**
  3663. * Creates the router service.
  3664. */
  3665. // TODO: vsavkin make internal after the final is out.
  3666. function Router(rootComponentType, urlSerializer, rootContexts, location, injector, loader, compiler, config) {
  3667. var _this = this;
  3668. this.rootComponentType = rootComponentType;
  3669. this.urlSerializer = urlSerializer;
  3670. this.rootContexts = rootContexts;
  3671. this.location = location;
  3672. this.config = config;
  3673. this.lastSuccessfulNavigation = null;
  3674. this.currentNavigation = null;
  3675. this.navigationId = 0;
  3676. this.isNgZoneEnabled = false;
  3677. /**
  3678. * An event stream for routing events in this NgModule.
  3679. */
  3680. this.events = new Subject();
  3681. /**
  3682. * A handler for navigation errors in this NgModule.
  3683. */
  3684. this.errorHandler = defaultErrorHandler;
  3685. /**
  3686. * Malformed uri error handler is invoked when `Router.parseUrl(url)` throws an
  3687. * error due to containing an invalid character. The most common case would be a `%` sign
  3688. * that's not encoded and is not part of a percent encoded sequence.
  3689. */
  3690. this.malformedUriErrorHandler = defaultMalformedUriErrorHandler;
  3691. /**
  3692. * True if at least one navigation event has occurred,
  3693. * false otherwise.
  3694. */
  3695. this.navigated = false;
  3696. this.lastSuccessfulId = -1;
  3697. /**
  3698. * Hooks that enable you to pause navigation,
  3699. * either before or after the preactivation phase.
  3700. * Used by `RouterModule`.
  3701. *
  3702. * @internal
  3703. */
  3704. this.hooks = {
  3705. beforePreactivation: defaultRouterHook,
  3706. afterPreactivation: defaultRouterHook
  3707. };
  3708. /**
  3709. * Extracts and merges URLs. Used for AngularJS to Angular migrations.
  3710. */
  3711. this.urlHandlingStrategy = new DefaultUrlHandlingStrategy();
  3712. /**
  3713. * The strategy for re-using routes.
  3714. */
  3715. this.routeReuseStrategy = new DefaultRouteReuseStrategy();
  3716. /**
  3717. * How to handle a navigation request to the current URL. One of:
  3718. * - `'ignore'` : The router ignores the request.
  3719. * - `'reload'` : The router reloads the URL. Use to implement a "refresh" feature.
  3720. */
  3721. this.onSameUrlNavigation = 'ignore';
  3722. /**
  3723. * How to merge parameters, data, and resolved data from parent to child
  3724. * routes. One of:
  3725. *
  3726. * - `'emptyOnly'` : Inherit parent parameters, data, and resolved data
  3727. * for path-less or component-less routes.
  3728. * - `'always'` : Inherit parent parameters, data, and resolved data
  3729. * for all child routes.
  3730. */
  3731. this.paramsInheritanceStrategy = 'emptyOnly';
  3732. /**
  3733. * Defines when the router updates the browser URL. The default behavior is to update after
  3734. * successful navigation. However, some applications may prefer a mode where the URL gets
  3735. * updated at the beginning of navigation. The most common use case would be updating the
  3736. * URL early so if navigation fails, you can show an error message with the URL that failed.
  3737. * Available options are:
  3738. *
  3739. * - `'deferred'`, the default, updates the browser URL after navigation has finished.
  3740. * - `'eager'`, updates browser URL at the beginning of navigation.
  3741. */
  3742. this.urlUpdateStrategy = 'deferred';
  3743. /**
  3744. * See {@link RouterModule} for more information.
  3745. */
  3746. this.relativeLinkResolution = 'legacy';
  3747. var onLoadStart = function (r) { return _this.triggerEvent(new RouteConfigLoadStart(r)); };
  3748. var onLoadEnd = function (r) { return _this.triggerEvent(new RouteConfigLoadEnd(r)); };
  3749. this.ngModule = injector.get(NgModuleRef);
  3750. this.console = injector.get(ɵConsole);
  3751. var ngZone = injector.get(NgZone);
  3752. this.isNgZoneEnabled = ngZone instanceof NgZone;
  3753. this.resetConfig(config);
  3754. this.currentUrlTree = createEmptyUrlTree();
  3755. this.rawUrlTree = this.currentUrlTree;
  3756. this.browserUrlTree = this.currentUrlTree;
  3757. this.configLoader = new RouterConfigLoader(loader, compiler, onLoadStart, onLoadEnd);
  3758. this.routerState = createEmptyState(this.currentUrlTree, this.rootComponentType);
  3759. this.transitions = new BehaviorSubject({
  3760. id: 0,
  3761. currentUrlTree: this.currentUrlTree,
  3762. currentRawUrl: this.currentUrlTree,
  3763. extractedUrl: this.urlHandlingStrategy.extract(this.currentUrlTree),
  3764. urlAfterRedirects: this.urlHandlingStrategy.extract(this.currentUrlTree),
  3765. rawUrl: this.currentUrlTree,
  3766. extras: {},
  3767. resolve: null,
  3768. reject: null,
  3769. promise: Promise.resolve(true),
  3770. source: 'imperative',
  3771. restoredState: null,
  3772. currentSnapshot: this.routerState.snapshot,
  3773. targetSnapshot: null,
  3774. currentRouterState: this.routerState,
  3775. targetRouterState: null,
  3776. guards: { canActivateChecks: [], canDeactivateChecks: [] },
  3777. guardsResult: null,
  3778. });
  3779. this.navigations = this.setupNavigations(this.transitions);
  3780. this.processNavigations();
  3781. }
  3782. Router.prototype.setupNavigations = function (transitions) {
  3783. var _this = this;
  3784. var eventsSubject = this.events;
  3785. return transitions.pipe(filter(function (t) { return t.id !== 0; }),
  3786. // Extract URL
  3787. map(function (t) { return (__assign({}, t, { extractedUrl: _this.urlHandlingStrategy.extract(t.rawUrl) })); }),
  3788. // Using switchMap so we cancel executing navigations when a new one comes in
  3789. switchMap(function (t) {
  3790. var completed = false;
  3791. var errored = false;
  3792. return of(t).pipe(
  3793. // Store the Navigation object
  3794. tap(function (t) {
  3795. _this.currentNavigation = {
  3796. id: t.id,
  3797. initialUrl: t.currentRawUrl,
  3798. extractedUrl: t.extractedUrl,
  3799. trigger: t.source,
  3800. extras: t.extras,
  3801. previousNavigation: _this.lastSuccessfulNavigation ? __assign({}, _this.lastSuccessfulNavigation, { previousNavigation: null }) :
  3802. null
  3803. };
  3804. }), switchMap(function (t) {
  3805. var urlTransition = !_this.navigated || t.extractedUrl.toString() !== _this.browserUrlTree.toString();
  3806. var processCurrentUrl = (_this.onSameUrlNavigation === 'reload' ? true : urlTransition) &&
  3807. _this.urlHandlingStrategy.shouldProcessUrl(t.rawUrl);
  3808. if (processCurrentUrl) {
  3809. return of(t).pipe(
  3810. // Fire NavigationStart event
  3811. switchMap(function (t) {
  3812. var transition = _this.transitions.getValue();
  3813. eventsSubject.next(new NavigationStart(t.id, _this.serializeUrl(t.extractedUrl), t.source, t.restoredState));
  3814. if (transition !== _this.transitions.getValue()) {
  3815. return EMPTY;
  3816. }
  3817. return [t];
  3818. }),
  3819. // This delay is required to match old behavior that forced navigation to
  3820. // always be async
  3821. switchMap(function (t) { return Promise.resolve(t); }),
  3822. // ApplyRedirects
  3823. applyRedirects$1(_this.ngModule.injector, _this.configLoader, _this.urlSerializer, _this.config),
  3824. // Update the currentNavigation
  3825. tap(function (t) {
  3826. _this.currentNavigation = __assign({}, _this.currentNavigation, { finalUrl: t.urlAfterRedirects });
  3827. }),
  3828. // Recognize
  3829. recognize$1(_this.rootComponentType, _this.config, function (url) { return _this.serializeUrl(url); }, _this.paramsInheritanceStrategy, _this.relativeLinkResolution),
  3830. // Update URL if in `eager` update mode
  3831. tap(function (t) {
  3832. if (_this.urlUpdateStrategy === 'eager') {
  3833. if (!t.extras.skipLocationChange) {
  3834. _this.setBrowserUrl(t.urlAfterRedirects, !!t.extras.replaceUrl, t.id, t.extras.state);
  3835. }
  3836. _this.browserUrlTree = t.urlAfterRedirects;
  3837. }
  3838. }),
  3839. // Fire RoutesRecognized
  3840. tap(function (t) {
  3841. var routesRecognized = new RoutesRecognized(t.id, _this.serializeUrl(t.extractedUrl), _this.serializeUrl(t.urlAfterRedirects), t.targetSnapshot);
  3842. eventsSubject.next(routesRecognized);
  3843. }));
  3844. }
  3845. else {
  3846. var processPreviousUrl = urlTransition && _this.rawUrlTree &&
  3847. _this.urlHandlingStrategy.shouldProcessUrl(_this.rawUrlTree);
  3848. /* When the current URL shouldn't be processed, but the previous one was, we
  3849. * handle this "error condition" by navigating to the previously successful URL,
  3850. * but leaving the URL intact.*/
  3851. if (processPreviousUrl) {
  3852. var id = t.id, extractedUrl = t.extractedUrl, source = t.source, restoredState = t.restoredState, extras = t.extras;
  3853. var navStart = new NavigationStart(id, _this.serializeUrl(extractedUrl), source, restoredState);
  3854. eventsSubject.next(navStart);
  3855. var targetSnapshot = createEmptyState(extractedUrl, _this.rootComponentType).snapshot;
  3856. return of(__assign({}, t, { targetSnapshot: targetSnapshot, urlAfterRedirects: extractedUrl, extras: __assign({}, extras, { skipLocationChange: false, replaceUrl: false }) }));
  3857. }
  3858. else {
  3859. /* When neither the current or previous URL can be processed, do nothing other
  3860. * than update router's internal reference to the current "settled" URL. This
  3861. * way the next navigation will be coming from the current URL in the browser.
  3862. */
  3863. _this.rawUrlTree = t.rawUrl;
  3864. _this.browserUrlTree = t.urlAfterRedirects;
  3865. t.resolve(null);
  3866. return EMPTY;
  3867. }
  3868. }
  3869. }),
  3870. // Before Preactivation
  3871. switchTap(function (t) {
  3872. var targetSnapshot = t.targetSnapshot, navigationId = t.id, appliedUrlTree = t.extractedUrl, rawUrlTree = t.rawUrl, _a = t.extras, skipLocationChange = _a.skipLocationChange, replaceUrl = _a.replaceUrl;
  3873. return _this.hooks.beforePreactivation(targetSnapshot, {
  3874. navigationId: navigationId,
  3875. appliedUrlTree: appliedUrlTree,
  3876. rawUrlTree: rawUrlTree,
  3877. skipLocationChange: !!skipLocationChange,
  3878. replaceUrl: !!replaceUrl,
  3879. });
  3880. }),
  3881. // --- GUARDS ---
  3882. tap(function (t) {
  3883. var guardsStart = new GuardsCheckStart(t.id, _this.serializeUrl(t.extractedUrl), _this.serializeUrl(t.urlAfterRedirects), t.targetSnapshot);
  3884. _this.triggerEvent(guardsStart);
  3885. }), map(function (t) { return (__assign({}, t, { guards: getAllRouteGuards(t.targetSnapshot, t.currentSnapshot, _this.rootContexts) })); }), checkGuards(_this.ngModule.injector, function (evt) { return _this.triggerEvent(evt); }), tap(function (t) {
  3886. if (isUrlTree(t.guardsResult)) {
  3887. var error = navigationCancelingError("Redirecting to \"" + _this.serializeUrl(t.guardsResult) + "\"");
  3888. error.url = t.guardsResult;
  3889. throw error;
  3890. }
  3891. }), tap(function (t) {
  3892. var guardsEnd = new GuardsCheckEnd(t.id, _this.serializeUrl(t.extractedUrl), _this.serializeUrl(t.urlAfterRedirects), t.targetSnapshot, !!t.guardsResult);
  3893. _this.triggerEvent(guardsEnd);
  3894. }), filter(function (t) {
  3895. if (!t.guardsResult) {
  3896. _this.resetUrlToCurrentUrlTree();
  3897. var navCancel = new NavigationCancel(t.id, _this.serializeUrl(t.extractedUrl), '');
  3898. eventsSubject.next(navCancel);
  3899. t.resolve(false);
  3900. return false;
  3901. }
  3902. return true;
  3903. }),
  3904. // --- RESOLVE ---
  3905. switchTap(function (t) {
  3906. if (t.guards.canActivateChecks.length) {
  3907. return of(t).pipe(tap(function (t) {
  3908. var resolveStart = new ResolveStart(t.id, _this.serializeUrl(t.extractedUrl), _this.serializeUrl(t.urlAfterRedirects), t.targetSnapshot);
  3909. _this.triggerEvent(resolveStart);
  3910. }), resolveData(_this.paramsInheritanceStrategy, _this.ngModule.injector), //
  3911. tap(function (t) {
  3912. var resolveEnd = new ResolveEnd(t.id, _this.serializeUrl(t.extractedUrl), _this.serializeUrl(t.urlAfterRedirects), t.targetSnapshot);
  3913. _this.triggerEvent(resolveEnd);
  3914. }));
  3915. }
  3916. return undefined;
  3917. }),
  3918. // --- AFTER PREACTIVATION ---
  3919. switchTap(function (t) {
  3920. var targetSnapshot = t.targetSnapshot, navigationId = t.id, appliedUrlTree = t.extractedUrl, rawUrlTree = t.rawUrl, _a = t.extras, skipLocationChange = _a.skipLocationChange, replaceUrl = _a.replaceUrl;
  3921. return _this.hooks.afterPreactivation(targetSnapshot, {
  3922. navigationId: navigationId,
  3923. appliedUrlTree: appliedUrlTree,
  3924. rawUrlTree: rawUrlTree,
  3925. skipLocationChange: !!skipLocationChange,
  3926. replaceUrl: !!replaceUrl,
  3927. });
  3928. }), map(function (t) {
  3929. var targetRouterState = createRouterState(_this.routeReuseStrategy, t.targetSnapshot, t.currentRouterState);
  3930. return (__assign({}, t, { targetRouterState: targetRouterState }));
  3931. }),
  3932. /* Once here, we are about to activate syncronously. The assumption is this will
  3933. succeed, and user code may read from the Router service. Therefore before
  3934. activation, we need to update router properties storing the current URL and the
  3935. RouterState, as well as updated the browser URL. All this should happen *before*
  3936. activating. */
  3937. tap(function (t) {
  3938. _this.currentUrlTree = t.urlAfterRedirects;
  3939. _this.rawUrlTree = _this.urlHandlingStrategy.merge(_this.currentUrlTree, t.rawUrl);
  3940. _this.routerState = t.targetRouterState;
  3941. if (_this.urlUpdateStrategy === 'deferred') {
  3942. if (!t.extras.skipLocationChange) {
  3943. _this.setBrowserUrl(_this.rawUrlTree, !!t.extras.replaceUrl, t.id, t.extras.state);
  3944. }
  3945. _this.browserUrlTree = t.urlAfterRedirects;
  3946. }
  3947. }), activateRoutes(_this.rootContexts, _this.routeReuseStrategy, function (evt) { return _this.triggerEvent(evt); }), tap({ next: function () { completed = true; }, complete: function () { completed = true; } }), finalize(function () {
  3948. /* When the navigation stream finishes either through error or success, we set the
  3949. * `completed` or `errored` flag. However, there are some situations where we could
  3950. * get here without either of those being set. For instance, a redirect during
  3951. * NavigationStart. Therefore, this is a catch-all to make sure the NavigationCancel
  3952. * event is fired when a navigation gets cancelled but not caught by other means. */
  3953. if (!completed && !errored) {
  3954. // Must reset to current URL tree here to ensure history.state is set. On a fresh
  3955. // page load, if a new navigation comes in before a successful navigation
  3956. // completes, there will be nothing in history.state.navigationId. This can cause
  3957. // sync problems with AngularJS sync code which looks for a value here in order
  3958. // to determine whether or not to handle a given popstate event or to leave it
  3959. // to the Angualr router.
  3960. _this.resetUrlToCurrentUrlTree();
  3961. var navCancel = new NavigationCancel(t.id, _this.serializeUrl(t.extractedUrl), "Navigation ID " + t.id + " is not equal to the current navigation id " + _this.navigationId);
  3962. eventsSubject.next(navCancel);
  3963. t.resolve(false);
  3964. }
  3965. // currentNavigation should always be reset to null here. If navigation was
  3966. // successful, lastSuccessfulTransition will have already been set. Therefore we
  3967. // can safely set currentNavigation to null here.
  3968. _this.currentNavigation = null;
  3969. }), catchError(function (e) {
  3970. errored = true;
  3971. /* This error type is issued during Redirect, and is handled as a cancellation
  3972. * rather than an error. */
  3973. if (isNavigationCancelingError(e)) {
  3974. var redirecting = isUrlTree(e.url);
  3975. if (!redirecting) {
  3976. // Set property only if we're not redirecting. If we landed on a page and
  3977. // redirect to `/` route, the new navigation is going to see the `/` isn't
  3978. // a change from the default currentUrlTree and won't navigate. This is
  3979. // only applicable with initial navigation, so setting `navigated` only when
  3980. // not redirecting resolves this scenario.
  3981. _this.navigated = true;
  3982. _this.resetStateAndUrl(t.currentRouterState, t.currentUrlTree, t.rawUrl);
  3983. }
  3984. var navCancel = new NavigationCancel(t.id, _this.serializeUrl(t.extractedUrl), e.message);
  3985. eventsSubject.next(navCancel);
  3986. t.resolve(false);
  3987. if (redirecting) {
  3988. _this.navigateByUrl(e.url);
  3989. }
  3990. /* All other errors should reset to the router's internal URL reference to the
  3991. * pre-error state. */
  3992. }
  3993. else {
  3994. _this.resetStateAndUrl(t.currentRouterState, t.currentUrlTree, t.rawUrl);
  3995. var navError = new NavigationError(t.id, _this.serializeUrl(t.extractedUrl), e);
  3996. eventsSubject.next(navError);
  3997. try {
  3998. t.resolve(_this.errorHandler(e));
  3999. }
  4000. catch (ee) {
  4001. t.reject(ee);
  4002. }
  4003. }
  4004. return EMPTY;
  4005. }));
  4006. // TODO(jasonaden): remove cast once g3 is on updated TypeScript
  4007. }));
  4008. };
  4009. /**
  4010. * @internal
  4011. * TODO: this should be removed once the constructor of the router made internal
  4012. */
  4013. Router.prototype.resetRootComponentType = function (rootComponentType) {
  4014. this.rootComponentType = rootComponentType;
  4015. // TODO: vsavkin router 4.0 should make the root component set to null
  4016. // this will simplify the lifecycle of the router.
  4017. this.routerState.root.component = this.rootComponentType;
  4018. };
  4019. Router.prototype.getTransition = function () {
  4020. var transition = this.transitions.value;
  4021. // This value needs to be set. Other values such as extractedUrl are set on initial navigation
  4022. // but the urlAfterRedirects may not get set if we aren't processing the new URL *and* not
  4023. // processing the previous URL.
  4024. transition.urlAfterRedirects = this.browserUrlTree;
  4025. return transition;
  4026. };
  4027. Router.prototype.setTransition = function (t) {
  4028. this.transitions.next(__assign({}, this.getTransition(), t));
  4029. };
  4030. /**
  4031. * Sets up the location change listener and performs the initial navigation.
  4032. */
  4033. Router.prototype.initialNavigation = function () {
  4034. this.setUpLocationChangeListener();
  4035. if (this.navigationId === 0) {
  4036. this.navigateByUrl(this.location.path(true), { replaceUrl: true });
  4037. }
  4038. };
  4039. /**
  4040. * Sets up the location change listener.
  4041. */
  4042. Router.prototype.setUpLocationChangeListener = function () {
  4043. var _this = this;
  4044. // Don't need to use Zone.wrap any more, because zone.js
  4045. // already patch onPopState, so location change callback will
  4046. // run into ngZone
  4047. if (!this.locationSubscription) {
  4048. this.locationSubscription = this.location.subscribe(function (change) {
  4049. var rawUrlTree = _this.parseUrl(change['url']);
  4050. var source = change['type'] === 'popstate' ? 'popstate' : 'hashchange';
  4051. // Navigations coming from Angular router have a navigationId state property. When this
  4052. // exists, restore the state.
  4053. var state = change.state && change.state.navigationId ? change.state : null;
  4054. setTimeout(function () { _this.scheduleNavigation(rawUrlTree, source, state, { replaceUrl: true }); }, 0);
  4055. });
  4056. }
  4057. };
  4058. Object.defineProperty(Router.prototype, "url", {
  4059. /** The current URL. */
  4060. get: function () { return this.serializeUrl(this.currentUrlTree); },
  4061. enumerable: true,
  4062. configurable: true
  4063. });
  4064. /** The current Navigation object if one exists */
  4065. Router.prototype.getCurrentNavigation = function () { return this.currentNavigation; };
  4066. /** @internal */
  4067. Router.prototype.triggerEvent = function (event) { this.events.next(event); };
  4068. /**
  4069. * Resets the configuration used for navigation and generating links.
  4070. *
  4071. * @param config The route array for the new configuration.
  4072. *
  4073. * @usageNotes
  4074. *
  4075. * ```
  4076. * router.resetConfig([
  4077. * { path: 'team/:id', component: TeamCmp, children: [
  4078. * { path: 'simple', component: SimpleCmp },
  4079. * { path: 'user/:name', component: UserCmp }
  4080. * ]}
  4081. * ]);
  4082. * ```
  4083. */
  4084. Router.prototype.resetConfig = function (config) {
  4085. validateConfig(config);
  4086. this.config = config.map(standardizeConfig);
  4087. this.navigated = false;
  4088. this.lastSuccessfulId = -1;
  4089. };
  4090. /** @docsNotRequired */
  4091. Router.prototype.ngOnDestroy = function () { this.dispose(); };
  4092. /** Disposes of the router. */
  4093. Router.prototype.dispose = function () {
  4094. if (this.locationSubscription) {
  4095. this.locationSubscription.unsubscribe();
  4096. this.locationSubscription = null;
  4097. }
  4098. };
  4099. /**
  4100. * Applies an array of commands to the current URL tree and creates a new URL tree.
  4101. *
  4102. * When given an activate route, applies the given commands starting from the route.
  4103. * When not given a route, applies the given command starting from the root.
  4104. *
  4105. * @param commands An array of commands to apply.
  4106. * @param navigationExtras
  4107. * @returns The new URL tree.
  4108. *
  4109. * @usageNotes
  4110. *
  4111. * ```
  4112. * // create /team/33/user/11
  4113. * router.createUrlTree(['/team', 33, 'user', 11]);
  4114. *
  4115. * // create /team/33;expand=true/user/11
  4116. * router.createUrlTree(['/team', 33, {expand: true}, 'user', 11]);
  4117. *
  4118. * // you can collapse static segments like this (this works only with the first passed-in value):
  4119. * router.createUrlTree(['/team/33/user', userId]);
  4120. *
  4121. * // If the first segment can contain slashes, and you do not want the router to split it, you
  4122. * // can do the following:
  4123. *
  4124. * router.createUrlTree([{segmentPath: '/one/two'}]);
  4125. *
  4126. * // create /team/33/(user/11//right:chat)
  4127. * router.createUrlTree(['/team', 33, {outlets: {primary: 'user/11', right: 'chat'}}]);
  4128. *
  4129. * // remove the right secondary node
  4130. * router.createUrlTree(['/team', 33, {outlets: {primary: 'user/11', right: null}}]);
  4131. *
  4132. * // assuming the current url is `/team/33/user/11` and the route points to `user/11`
  4133. *
  4134. * // navigate to /team/33/user/11/details
  4135. * router.createUrlTree(['details'], {relativeTo: route});
  4136. *
  4137. * // navigate to /team/33/user/22
  4138. * router.createUrlTree(['../22'], {relativeTo: route});
  4139. *
  4140. * // navigate to /team/44/user/22
  4141. * router.createUrlTree(['../../team/44/user/22'], {relativeTo: route});
  4142. * ```
  4143. */
  4144. Router.prototype.createUrlTree = function (commands, navigationExtras) {
  4145. if (navigationExtras === void 0) { navigationExtras = {}; }
  4146. var relativeTo = navigationExtras.relativeTo, queryParams = navigationExtras.queryParams, fragment = navigationExtras.fragment, preserveQueryParams = navigationExtras.preserveQueryParams, queryParamsHandling = navigationExtras.queryParamsHandling, preserveFragment = navigationExtras.preserveFragment;
  4147. if (isDevMode() && preserveQueryParams && console && console.warn) {
  4148. console.warn('preserveQueryParams is deprecated, use queryParamsHandling instead.');
  4149. }
  4150. var a = relativeTo || this.routerState.root;
  4151. var f = preserveFragment ? this.currentUrlTree.fragment : fragment;
  4152. var q = null;
  4153. if (queryParamsHandling) {
  4154. switch (queryParamsHandling) {
  4155. case 'merge':
  4156. q = __assign({}, this.currentUrlTree.queryParams, queryParams);
  4157. break;
  4158. case 'preserve':
  4159. q = this.currentUrlTree.queryParams;
  4160. break;
  4161. default:
  4162. q = queryParams || null;
  4163. }
  4164. }
  4165. else {
  4166. q = preserveQueryParams ? this.currentUrlTree.queryParams : queryParams || null;
  4167. }
  4168. if (q !== null) {
  4169. q = this.removeEmptyProps(q);
  4170. }
  4171. return createUrlTree(a, this.currentUrlTree, commands, q, f);
  4172. };
  4173. /**
  4174. * Navigate based on the provided URL, which must be absolute.
  4175. *
  4176. * @param url An absolute URL. The function does not apply any delta to the current URL.
  4177. * @param extras An object containing properties that modify the navigation strategy.
  4178. * The function ignores any properties in the `NavigationExtras` that would change the
  4179. * provided URL.
  4180. *
  4181. * @returns A Promise that resolves to 'true' when navigation succeeds,
  4182. * to 'false' when navigation fails, or is rejected on error.
  4183. *
  4184. * @usageNotes
  4185. *
  4186. * ### Example
  4187. *
  4188. * ```
  4189. * router.navigateByUrl("/team/33/user/11");
  4190. *
  4191. * // Navigate without updating the URL
  4192. * router.navigateByUrl("/team/33/user/11", { skipLocationChange: true });
  4193. * ```
  4194. *
  4195. */
  4196. Router.prototype.navigateByUrl = function (url, extras) {
  4197. if (extras === void 0) { extras = { skipLocationChange: false }; }
  4198. if (isDevMode() && this.isNgZoneEnabled && !NgZone.isInAngularZone()) {
  4199. this.console.warn("Navigation triggered outside Angular zone, did you forget to call 'ngZone.run()'?");
  4200. }
  4201. var urlTree = isUrlTree(url) ? url : this.parseUrl(url);
  4202. var mergedTree = this.urlHandlingStrategy.merge(urlTree, this.rawUrlTree);
  4203. return this.scheduleNavigation(mergedTree, 'imperative', null, extras);
  4204. };
  4205. /**
  4206. * Navigate based on the provided array of commands and a starting point.
  4207. * If no starting route is provided, the navigation is absolute.
  4208. *
  4209. * Returns a promise that:
  4210. * - resolves to 'true' when navigation succeeds,
  4211. * - resolves to 'false' when navigation fails,
  4212. * - is rejected when an error happens.
  4213. *
  4214. * @usageNotes
  4215. *
  4216. * ### Example
  4217. *
  4218. * ```
  4219. * router.navigate(['team', 33, 'user', 11], {relativeTo: route});
  4220. *
  4221. * // Navigate without updating the URL
  4222. * router.navigate(['team', 33, 'user', 11], {relativeTo: route, skipLocationChange: true});
  4223. * ```
  4224. *
  4225. * The first parameter of `navigate()` is a delta to be applied to the current URL
  4226. * or the one provided in the `relativeTo` property of the second parameter (the
  4227. * `NavigationExtras`).
  4228. *
  4229. * In order to affect this browser's `history.state` entry, the `state`
  4230. * parameter can be passed. This must be an object because the router
  4231. * will add the `navigationId` property to this object before creating
  4232. * the new history item.
  4233. */
  4234. Router.prototype.navigate = function (commands, extras) {
  4235. if (extras === void 0) { extras = { skipLocationChange: false }; }
  4236. validateCommands(commands);
  4237. return this.navigateByUrl(this.createUrlTree(commands, extras), extras);
  4238. };
  4239. /** Serializes a `UrlTree` into a string */
  4240. Router.prototype.serializeUrl = function (url) { return this.urlSerializer.serialize(url); };
  4241. /** Parses a string into a `UrlTree` */
  4242. Router.prototype.parseUrl = function (url) {
  4243. var urlTree;
  4244. try {
  4245. urlTree = this.urlSerializer.parse(url);
  4246. }
  4247. catch (e) {
  4248. urlTree = this.malformedUriErrorHandler(e, this.urlSerializer, url);
  4249. }
  4250. return urlTree;
  4251. };
  4252. /** Returns whether the url is activated */
  4253. Router.prototype.isActive = function (url, exact) {
  4254. if (isUrlTree(url)) {
  4255. return containsTree(this.currentUrlTree, url, exact);
  4256. }
  4257. var urlTree = this.parseUrl(url);
  4258. return containsTree(this.currentUrlTree, urlTree, exact);
  4259. };
  4260. Router.prototype.removeEmptyProps = function (params) {
  4261. return Object.keys(params).reduce(function (result, key) {
  4262. var value = params[key];
  4263. if (value !== null && value !== undefined) {
  4264. result[key] = value;
  4265. }
  4266. return result;
  4267. }, {});
  4268. };
  4269. Router.prototype.processNavigations = function () {
  4270. var _this = this;
  4271. this.navigations.subscribe(function (t) {
  4272. _this.navigated = true;
  4273. _this.lastSuccessfulId = t.id;
  4274. _this.events
  4275. .next(new NavigationEnd(t.id, _this.serializeUrl(t.extractedUrl), _this.serializeUrl(_this.currentUrlTree)));
  4276. _this.lastSuccessfulNavigation = _this.currentNavigation;
  4277. _this.currentNavigation = null;
  4278. t.resolve(true);
  4279. }, function (e) { _this.console.warn("Unhandled Navigation Error: "); });
  4280. };
  4281. Router.prototype.scheduleNavigation = function (rawUrl, source, restoredState, extras) {
  4282. var lastNavigation = this.getTransition();
  4283. // If the user triggers a navigation imperatively (e.g., by using navigateByUrl),
  4284. // and that navigation results in 'replaceState' that leads to the same URL,
  4285. // we should skip those.
  4286. if (lastNavigation && source !== 'imperative' && lastNavigation.source === 'imperative' &&
  4287. lastNavigation.rawUrl.toString() === rawUrl.toString()) {
  4288. return Promise.resolve(true); // return value is not used
  4289. }
  4290. // Because of a bug in IE and Edge, the location class fires two events (popstate and
  4291. // hashchange) every single time. The second one should be ignored. Otherwise, the URL will
  4292. // flicker. Handles the case when a popstate was emitted first.
  4293. if (lastNavigation && source == 'hashchange' && lastNavigation.source === 'popstate' &&
  4294. lastNavigation.rawUrl.toString() === rawUrl.toString()) {
  4295. return Promise.resolve(true); // return value is not used
  4296. }
  4297. // Because of a bug in IE and Edge, the location class fires two events (popstate and
  4298. // hashchange) every single time. The second one should be ignored. Otherwise, the URL will
  4299. // flicker. Handles the case when a hashchange was emitted first.
  4300. if (lastNavigation && source == 'popstate' && lastNavigation.source === 'hashchange' &&
  4301. lastNavigation.rawUrl.toString() === rawUrl.toString()) {
  4302. return Promise.resolve(true); // return value is not used
  4303. }
  4304. var resolve = null;
  4305. var reject = null;
  4306. var promise = new Promise(function (res, rej) {
  4307. resolve = res;
  4308. reject = rej;
  4309. });
  4310. var id = ++this.navigationId;
  4311. this.setTransition({
  4312. id: id,
  4313. source: source,
  4314. restoredState: restoredState,
  4315. currentUrlTree: this.currentUrlTree,
  4316. currentRawUrl: this.rawUrlTree, rawUrl: rawUrl, extras: extras, resolve: resolve, reject: reject, promise: promise,
  4317. currentSnapshot: this.routerState.snapshot,
  4318. currentRouterState: this.routerState
  4319. });
  4320. // Make sure that the error is propagated even though `processNavigations` catch
  4321. // handler does not rethrow
  4322. return promise.catch(function (e) { return Promise.reject(e); });
  4323. };
  4324. Router.prototype.setBrowserUrl = function (url, replaceUrl, id, state) {
  4325. var path = this.urlSerializer.serialize(url);
  4326. state = state || {};
  4327. if (this.location.isCurrentPathEqualTo(path) || replaceUrl) {
  4328. // TODO(jasonaden): Remove first `navigationId` and rely on `ng` namespace.
  4329. this.location.replaceState(path, '', __assign({}, state, { navigationId: id }));
  4330. }
  4331. else {
  4332. this.location.go(path, '', __assign({}, state, { navigationId: id }));
  4333. }
  4334. };
  4335. Router.prototype.resetStateAndUrl = function (storedState, storedUrl, rawUrl) {
  4336. this.routerState = storedState;
  4337. this.currentUrlTree = storedUrl;
  4338. this.rawUrlTree = this.urlHandlingStrategy.merge(this.currentUrlTree, rawUrl);
  4339. this.resetUrlToCurrentUrlTree();
  4340. };
  4341. Router.prototype.resetUrlToCurrentUrlTree = function () {
  4342. this.location.replaceState(this.urlSerializer.serialize(this.rawUrlTree), '', { navigationId: this.lastSuccessfulId });
  4343. };
  4344. return Router;
  4345. }());
  4346. function validateCommands(commands) {
  4347. for (var i = 0; i < commands.length; i++) {
  4348. var cmd = commands[i];
  4349. if (cmd == null) {
  4350. throw new Error("The requested path contains " + cmd + " segment at index " + i);
  4351. }
  4352. }
  4353. }
  4354. /**
  4355. * @license
  4356. * Copyright Google Inc. All Rights Reserved.
  4357. *
  4358. * Use of this source code is governed by an MIT-style license that can be
  4359. * found in the LICENSE file at https://angular.io/license
  4360. */
  4361. /**
  4362. * @description
  4363. *
  4364. * Lets you link to specific routes in your app.
  4365. *
  4366. * Consider the following route configuration:
  4367. * `[{ path: 'user/:name', component: UserCmp }]`.
  4368. * When linking to this `user/:name` route, you use the `RouterLink` directive.
  4369. *
  4370. * If the link is static, you can use the directive as follows:
  4371. * `<a routerLink="/user/bob">link to user component</a>`
  4372. *
  4373. * If you use dynamic values to generate the link, you can pass an array of path
  4374. * segments, followed by the params for each segment.
  4375. *
  4376. * For instance `['/team', teamId, 'user', userName, {details: true}]`
  4377. * means that we want to generate a link to `/team/11/user/bob;details=true`.
  4378. *
  4379. * Multiple static segments can be merged into one
  4380. * (e.g., `['/team/11/user', userName, {details: true}]`).
  4381. *
  4382. * The first segment name can be prepended with `/`, `./`, or `../`:
  4383. * * If the first segment begins with `/`, the router will look up the route from the root of the
  4384. * app.
  4385. * * If the first segment begins with `./`, or doesn't begin with a slash, the router will
  4386. * instead look in the children of the current activated route.
  4387. * * And if the first segment begins with `../`, the router will go up one level.
  4388. *
  4389. * You can set query params and fragment as follows:
  4390. *
  4391. * ```
  4392. * <a [routerLink]="['/user/bob']" [queryParams]="{debug: true}" fragment="education">
  4393. * link to user component
  4394. * </a>
  4395. * ```
  4396. * RouterLink will use these to generate this link: `/user/bob#education?debug=true`.
  4397. *
  4398. * (Deprecated in v4.0.0 use `queryParamsHandling` instead) You can also tell the
  4399. * directive to preserve the current query params and fragment:
  4400. *
  4401. * ```
  4402. * <a [routerLink]="['/user/bob']" preserveQueryParams preserveFragment>
  4403. * link to user component
  4404. * </a>
  4405. * ```
  4406. *
  4407. * You can tell the directive how to handle queryParams. Available options are:
  4408. * - `'merge'`: merge the queryParams into the current queryParams
  4409. * - `'preserve'`: preserve the current queryParams
  4410. * - default/`''`: use the queryParams only
  4411. *
  4412. * Same options for {@link NavigationExtras#queryParamsHandling
  4413. * NavigationExtras#queryParamsHandling}.
  4414. *
  4415. * ```
  4416. * <a [routerLink]="['/user/bob']" [queryParams]="{debug: true}" queryParamsHandling="merge">
  4417. * link to user component
  4418. * </a>
  4419. * ```
  4420. *
  4421. * You can provide a `state` value to be persisted to the browser's History.state
  4422. * property (See https://developer.mozilla.org/en-US/docs/Web/API/History#Properties). It's
  4423. * used as follows:
  4424. *
  4425. * ```
  4426. * <a [routerLink]="['/user/bob']" [state]="{tracingId: 123}">
  4427. * link to user component
  4428. * </a>
  4429. * ```
  4430. *
  4431. * And later the value can be read from the router through `router.getCurrentNavigation`.
  4432. * For example, to capture the `tracingId` above during the `NavigationStart` event:
  4433. *
  4434. * ```
  4435. * // Get NavigationStart events
  4436. * router.events.pipe(filter(e => e instanceof NavigationStart)).subscribe(e => {
  4437. * const navigation = router.getCurrentNavigation();
  4438. * tracingService.trace({id: navigation.extras.state.tracingId});
  4439. * });
  4440. * ```
  4441. *
  4442. * The router link directive always treats the provided input as a delta to the current url.
  4443. *
  4444. * For instance, if the current url is `/user/(box//aux:team)`.
  4445. *
  4446. * Then the following link `<a [routerLink]="['/user/jim']">Jim</a>` will generate the link
  4447. * `/user/(jim//aux:team)`.
  4448. *
  4449. * See {@link Router#createUrlTree createUrlTree} for more information.
  4450. *
  4451. * @ngModule RouterModule
  4452. *
  4453. * @publicApi
  4454. */
  4455. var RouterLink = /** @class */ (function () {
  4456. function RouterLink(router, route, tabIndex, renderer, el) {
  4457. this.router = router;
  4458. this.route = route;
  4459. this.commands = [];
  4460. if (tabIndex == null) {
  4461. renderer.setAttribute(el.nativeElement, 'tabindex', '0');
  4462. }
  4463. }
  4464. Object.defineProperty(RouterLink.prototype, "routerLink", {
  4465. set: function (commands) {
  4466. if (commands != null) {
  4467. this.commands = Array.isArray(commands) ? commands : [commands];
  4468. }
  4469. else {
  4470. this.commands = [];
  4471. }
  4472. },
  4473. enumerable: true,
  4474. configurable: true
  4475. });
  4476. Object.defineProperty(RouterLink.prototype, "preserveQueryParams", {
  4477. /**
  4478. * @deprecated 4.0.0 use `queryParamsHandling` instead.
  4479. */
  4480. set: function (value) {
  4481. if (isDevMode() && console && console.warn) {
  4482. console.warn('preserveQueryParams is deprecated!, use queryParamsHandling instead.');
  4483. }
  4484. this.preserve = value;
  4485. },
  4486. enumerable: true,
  4487. configurable: true
  4488. });
  4489. RouterLink.prototype.onClick = function () {
  4490. var extras = {
  4491. skipLocationChange: attrBoolValue(this.skipLocationChange),
  4492. replaceUrl: attrBoolValue(this.replaceUrl),
  4493. };
  4494. this.router.navigateByUrl(this.urlTree, extras);
  4495. return true;
  4496. };
  4497. Object.defineProperty(RouterLink.prototype, "urlTree", {
  4498. get: function () {
  4499. return this.router.createUrlTree(this.commands, {
  4500. relativeTo: this.route,
  4501. queryParams: this.queryParams,
  4502. fragment: this.fragment,
  4503. preserveQueryParams: attrBoolValue(this.preserve),
  4504. queryParamsHandling: this.queryParamsHandling,
  4505. preserveFragment: attrBoolValue(this.preserveFragment),
  4506. });
  4507. },
  4508. enumerable: true,
  4509. configurable: true
  4510. });
  4511. __decorate([
  4512. Input(),
  4513. __metadata("design:type", Object)
  4514. ], RouterLink.prototype, "queryParams", void 0);
  4515. __decorate([
  4516. Input(),
  4517. __metadata("design:type", String)
  4518. ], RouterLink.prototype, "fragment", void 0);
  4519. __decorate([
  4520. Input(),
  4521. __metadata("design:type", String)
  4522. ], RouterLink.prototype, "queryParamsHandling", void 0);
  4523. __decorate([
  4524. Input(),
  4525. __metadata("design:type", Boolean)
  4526. ], RouterLink.prototype, "preserveFragment", void 0);
  4527. __decorate([
  4528. Input(),
  4529. __metadata("design:type", Boolean)
  4530. ], RouterLink.prototype, "skipLocationChange", void 0);
  4531. __decorate([
  4532. Input(),
  4533. __metadata("design:type", Boolean)
  4534. ], RouterLink.prototype, "replaceUrl", void 0);
  4535. __decorate([
  4536. Input(),
  4537. __metadata("design:type", Object)
  4538. ], RouterLink.prototype, "state", void 0);
  4539. __decorate([
  4540. Input(),
  4541. __metadata("design:type", Object),
  4542. __metadata("design:paramtypes", [Object])
  4543. ], RouterLink.prototype, "routerLink", null);
  4544. __decorate([
  4545. Input(),
  4546. __metadata("design:type", Boolean),
  4547. __metadata("design:paramtypes", [Boolean])
  4548. ], RouterLink.prototype, "preserveQueryParams", null);
  4549. __decorate([
  4550. HostListener('click'),
  4551. __metadata("design:type", Function),
  4552. __metadata("design:paramtypes", []),
  4553. __metadata("design:returntype", Boolean)
  4554. ], RouterLink.prototype, "onClick", null);
  4555. RouterLink = __decorate([
  4556. Directive({ selector: ':not(a):not(area)[routerLink]' }),
  4557. __param(2, Attribute('tabindex')),
  4558. __metadata("design:paramtypes", [Router, ActivatedRoute, String, Renderer2, ElementRef])
  4559. ], RouterLink);
  4560. return RouterLink;
  4561. }());
  4562. /**
  4563. * @description
  4564. *
  4565. * Lets you link to specific routes in your app.
  4566. *
  4567. * See `RouterLink` for more information.
  4568. *
  4569. * @ngModule RouterModule
  4570. *
  4571. * @publicApi
  4572. */
  4573. var RouterLinkWithHref = /** @class */ (function () {
  4574. function RouterLinkWithHref(router, route, locationStrategy) {
  4575. var _this = this;
  4576. this.router = router;
  4577. this.route = route;
  4578. this.locationStrategy = locationStrategy;
  4579. this.commands = [];
  4580. this.subscription = router.events.subscribe(function (s) {
  4581. if (s instanceof NavigationEnd) {
  4582. _this.updateTargetUrlAndHref();
  4583. }
  4584. });
  4585. }
  4586. Object.defineProperty(RouterLinkWithHref.prototype, "routerLink", {
  4587. set: function (commands) {
  4588. if (commands != null) {
  4589. this.commands = Array.isArray(commands) ? commands : [commands];
  4590. }
  4591. else {
  4592. this.commands = [];
  4593. }
  4594. },
  4595. enumerable: true,
  4596. configurable: true
  4597. });
  4598. Object.defineProperty(RouterLinkWithHref.prototype, "preserveQueryParams", {
  4599. set: function (value) {
  4600. if (isDevMode() && console && console.warn) {
  4601. console.warn('preserveQueryParams is deprecated, use queryParamsHandling instead.');
  4602. }
  4603. this.preserve = value;
  4604. },
  4605. enumerable: true,
  4606. configurable: true
  4607. });
  4608. RouterLinkWithHref.prototype.ngOnChanges = function (changes) { this.updateTargetUrlAndHref(); };
  4609. RouterLinkWithHref.prototype.ngOnDestroy = function () { this.subscription.unsubscribe(); };
  4610. RouterLinkWithHref.prototype.onClick = function (button, ctrlKey, metaKey, shiftKey) {
  4611. if (button !== 0 || ctrlKey || metaKey || shiftKey) {
  4612. return true;
  4613. }
  4614. if (typeof this.target === 'string' && this.target != '_self') {
  4615. return true;
  4616. }
  4617. var extras = {
  4618. skipLocationChange: attrBoolValue(this.skipLocationChange),
  4619. replaceUrl: attrBoolValue(this.replaceUrl),
  4620. state: this.state
  4621. };
  4622. this.router.navigateByUrl(this.urlTree, extras);
  4623. return false;
  4624. };
  4625. RouterLinkWithHref.prototype.updateTargetUrlAndHref = function () {
  4626. this.href = this.locationStrategy.prepareExternalUrl(this.router.serializeUrl(this.urlTree));
  4627. };
  4628. Object.defineProperty(RouterLinkWithHref.prototype, "urlTree", {
  4629. get: function () {
  4630. return this.router.createUrlTree(this.commands, {
  4631. relativeTo: this.route,
  4632. queryParams: this.queryParams,
  4633. fragment: this.fragment,
  4634. preserveQueryParams: attrBoolValue(this.preserve),
  4635. queryParamsHandling: this.queryParamsHandling,
  4636. preserveFragment: attrBoolValue(this.preserveFragment),
  4637. });
  4638. },
  4639. enumerable: true,
  4640. configurable: true
  4641. });
  4642. __decorate([
  4643. HostBinding('attr.target'), Input(),
  4644. __metadata("design:type", String)
  4645. ], RouterLinkWithHref.prototype, "target", void 0);
  4646. __decorate([
  4647. Input(),
  4648. __metadata("design:type", Object)
  4649. ], RouterLinkWithHref.prototype, "queryParams", void 0);
  4650. __decorate([
  4651. Input(),
  4652. __metadata("design:type", String)
  4653. ], RouterLinkWithHref.prototype, "fragment", void 0);
  4654. __decorate([
  4655. Input(),
  4656. __metadata("design:type", String)
  4657. ], RouterLinkWithHref.prototype, "queryParamsHandling", void 0);
  4658. __decorate([
  4659. Input(),
  4660. __metadata("design:type", Boolean)
  4661. ], RouterLinkWithHref.prototype, "preserveFragment", void 0);
  4662. __decorate([
  4663. Input(),
  4664. __metadata("design:type", Boolean)
  4665. ], RouterLinkWithHref.prototype, "skipLocationChange", void 0);
  4666. __decorate([
  4667. Input(),
  4668. __metadata("design:type", Boolean)
  4669. ], RouterLinkWithHref.prototype, "replaceUrl", void 0);
  4670. __decorate([
  4671. Input(),
  4672. __metadata("design:type", Object)
  4673. ], RouterLinkWithHref.prototype, "state", void 0);
  4674. __decorate([
  4675. HostBinding(),
  4676. __metadata("design:type", String)
  4677. ], RouterLinkWithHref.prototype, "href", void 0);
  4678. __decorate([
  4679. Input(),
  4680. __metadata("design:type", Object),
  4681. __metadata("design:paramtypes", [Object])
  4682. ], RouterLinkWithHref.prototype, "routerLink", null);
  4683. __decorate([
  4684. Input(),
  4685. __metadata("design:type", Boolean),
  4686. __metadata("design:paramtypes", [Boolean])
  4687. ], RouterLinkWithHref.prototype, "preserveQueryParams", null);
  4688. __decorate([
  4689. HostListener('click', ['$event.button', '$event.ctrlKey', '$event.metaKey', '$event.shiftKey']),
  4690. __metadata("design:type", Function),
  4691. __metadata("design:paramtypes", [Number, Boolean, Boolean, Boolean]),
  4692. __metadata("design:returntype", Boolean)
  4693. ], RouterLinkWithHref.prototype, "onClick", null);
  4694. RouterLinkWithHref = __decorate([
  4695. Directive({ selector: 'a[routerLink],area[routerLink]' }),
  4696. __metadata("design:paramtypes", [Router, ActivatedRoute,
  4697. LocationStrategy])
  4698. ], RouterLinkWithHref);
  4699. return RouterLinkWithHref;
  4700. }());
  4701. function attrBoolValue(s) {
  4702. return s === '' || !!s;
  4703. }
  4704. /**
  4705. * @license
  4706. * Copyright Google Inc. All Rights Reserved.
  4707. *
  4708. * Use of this source code is governed by an MIT-style license that can be
  4709. * found in the LICENSE file at https://angular.io/license
  4710. */
  4711. /**
  4712. *
  4713. * @description
  4714. *
  4715. * Lets you add a CSS class to an element when the link's route becomes active.
  4716. *
  4717. * This directive lets you add a CSS class to an element when the link's route
  4718. * becomes active.
  4719. *
  4720. * Consider the following example:
  4721. *
  4722. * ```
  4723. * <a routerLink="/user/bob" routerLinkActive="active-link">Bob</a>
  4724. * ```
  4725. *
  4726. * When the url is either '/user' or '/user/bob', the active-link class will
  4727. * be added to the `a` tag. If the url changes, the class will be removed.
  4728. *
  4729. * You can set more than one class, as follows:
  4730. *
  4731. * ```
  4732. * <a routerLink="/user/bob" routerLinkActive="class1 class2">Bob</a>
  4733. * <a routerLink="/user/bob" [routerLinkActive]="['class1', 'class2']">Bob</a>
  4734. * ```
  4735. *
  4736. * You can configure RouterLinkActive by passing `exact: true`. This will add the classes
  4737. * only when the url matches the link exactly.
  4738. *
  4739. * ```
  4740. * <a routerLink="/user/bob" routerLinkActive="active-link" [routerLinkActiveOptions]="{exact:
  4741. * true}">Bob</a>
  4742. * ```
  4743. *
  4744. * You can assign the RouterLinkActive instance to a template variable and directly check
  4745. * the `isActive` status.
  4746. * ```
  4747. * <a routerLink="/user/bob" routerLinkActive #rla="routerLinkActive">
  4748. * Bob {{ rla.isActive ? '(already open)' : ''}}
  4749. * </a>
  4750. * ```
  4751. *
  4752. * Finally, you can apply the RouterLinkActive directive to an ancestor of a RouterLink.
  4753. *
  4754. * ```
  4755. * <div routerLinkActive="active-link" [routerLinkActiveOptions]="{exact: true}">
  4756. * <a routerLink="/user/jim">Jim</a>
  4757. * <a routerLink="/user/bob">Bob</a>
  4758. * </div>
  4759. * ```
  4760. *
  4761. * This will set the active-link class on the div tag if the url is either '/user/jim' or
  4762. * '/user/bob'.
  4763. *
  4764. * @ngModule RouterModule
  4765. *
  4766. * @publicApi
  4767. */
  4768. var RouterLinkActive = /** @class */ (function () {
  4769. function RouterLinkActive(router, element, renderer, link, linkWithHref) {
  4770. var _this = this;
  4771. this.router = router;
  4772. this.element = element;
  4773. this.renderer = renderer;
  4774. this.link = link;
  4775. this.linkWithHref = linkWithHref;
  4776. this.classes = [];
  4777. this.isActive = false;
  4778. this.routerLinkActiveOptions = { exact: false };
  4779. this.subscription = router.events.subscribe(function (s) {
  4780. if (s instanceof NavigationEnd) {
  4781. _this.update();
  4782. }
  4783. });
  4784. }
  4785. RouterLinkActive.prototype.ngAfterContentInit = function () {
  4786. var _this = this;
  4787. this.links.changes.subscribe(function (_) { return _this.update(); });
  4788. this.linksWithHrefs.changes.subscribe(function (_) { return _this.update(); });
  4789. this.update();
  4790. };
  4791. Object.defineProperty(RouterLinkActive.prototype, "routerLinkActive", {
  4792. set: function (data) {
  4793. var classes = Array.isArray(data) ? data : data.split(' ');
  4794. this.classes = classes.filter(function (c) { return !!c; });
  4795. },
  4796. enumerable: true,
  4797. configurable: true
  4798. });
  4799. RouterLinkActive.prototype.ngOnChanges = function (changes) { this.update(); };
  4800. RouterLinkActive.prototype.ngOnDestroy = function () { this.subscription.unsubscribe(); };
  4801. RouterLinkActive.prototype.update = function () {
  4802. var _this = this;
  4803. if (!this.links || !this.linksWithHrefs || !this.router.navigated)
  4804. return;
  4805. Promise.resolve().then(function () {
  4806. var hasActiveLinks = _this.hasActiveLinks();
  4807. if (_this.isActive !== hasActiveLinks) {
  4808. _this.isActive = hasActiveLinks;
  4809. _this.classes.forEach(function (c) {
  4810. if (hasActiveLinks) {
  4811. _this.renderer.addClass(_this.element.nativeElement, c);
  4812. }
  4813. else {
  4814. _this.renderer.removeClass(_this.element.nativeElement, c);
  4815. }
  4816. });
  4817. }
  4818. });
  4819. };
  4820. RouterLinkActive.prototype.isLinkActive = function (router) {
  4821. var _this = this;
  4822. return function (link) {
  4823. return router.isActive(link.urlTree, _this.routerLinkActiveOptions.exact);
  4824. };
  4825. };
  4826. RouterLinkActive.prototype.hasActiveLinks = function () {
  4827. var isActiveCheckFn = this.isLinkActive(this.router);
  4828. return this.link && isActiveCheckFn(this.link) ||
  4829. this.linkWithHref && isActiveCheckFn(this.linkWithHref) ||
  4830. this.links.some(isActiveCheckFn) || this.linksWithHrefs.some(isActiveCheckFn);
  4831. };
  4832. __decorate([
  4833. ContentChildren(RouterLink, { descendants: true }),
  4834. __metadata("design:type", QueryList)
  4835. ], RouterLinkActive.prototype, "links", void 0);
  4836. __decorate([
  4837. ContentChildren(RouterLinkWithHref, { descendants: true }),
  4838. __metadata("design:type", QueryList)
  4839. ], RouterLinkActive.prototype, "linksWithHrefs", void 0);
  4840. __decorate([
  4841. Input(),
  4842. __metadata("design:type", Object)
  4843. ], RouterLinkActive.prototype, "routerLinkActiveOptions", void 0);
  4844. __decorate([
  4845. Input(),
  4846. __metadata("design:type", Object),
  4847. __metadata("design:paramtypes", [Object])
  4848. ], RouterLinkActive.prototype, "routerLinkActive", null);
  4849. RouterLinkActive = __decorate([
  4850. Directive({
  4851. selector: '[routerLinkActive]',
  4852. exportAs: 'routerLinkActive',
  4853. }),
  4854. __param(3, Optional()),
  4855. __param(4, Optional()),
  4856. __metadata("design:paramtypes", [Router, ElementRef, Renderer2,
  4857. RouterLink,
  4858. RouterLinkWithHref])
  4859. ], RouterLinkActive);
  4860. return RouterLinkActive;
  4861. }());
  4862. /**
  4863. * @license
  4864. * Copyright Google Inc. All Rights Reserved.
  4865. *
  4866. * Use of this source code is governed by an MIT-style license that can be
  4867. * found in the LICENSE file at https://angular.io/license
  4868. */
  4869. /**
  4870. * Store contextual information about a `RouterOutlet`
  4871. *
  4872. * @publicApi
  4873. */
  4874. var OutletContext = /** @class */ (function () {
  4875. function OutletContext() {
  4876. this.outlet = null;
  4877. this.route = null;
  4878. this.resolver = null;
  4879. this.children = new ChildrenOutletContexts();
  4880. this.attachRef = null;
  4881. }
  4882. return OutletContext;
  4883. }());
  4884. /**
  4885. * Store contextual information about the children (= nested) `RouterOutlet`
  4886. *
  4887. * @publicApi
  4888. */
  4889. var ChildrenOutletContexts = /** @class */ (function () {
  4890. function ChildrenOutletContexts() {
  4891. // contexts for child outlets, by name.
  4892. this.contexts = new Map();
  4893. }
  4894. /** Called when a `RouterOutlet` directive is instantiated */
  4895. ChildrenOutletContexts.prototype.onChildOutletCreated = function (childName, outlet) {
  4896. var context = this.getOrCreateContext(childName);
  4897. context.outlet = outlet;
  4898. this.contexts.set(childName, context);
  4899. };
  4900. /**
  4901. * Called when a `RouterOutlet` directive is destroyed.
  4902. * We need to keep the context as the outlet could be destroyed inside a NgIf and might be
  4903. * re-created later.
  4904. */
  4905. ChildrenOutletContexts.prototype.onChildOutletDestroyed = function (childName) {
  4906. var context = this.getContext(childName);
  4907. if (context) {
  4908. context.outlet = null;
  4909. }
  4910. };
  4911. /**
  4912. * Called when the corresponding route is deactivated during navigation.
  4913. * Because the component get destroyed, all children outlet are destroyed.
  4914. */
  4915. ChildrenOutletContexts.prototype.onOutletDeactivated = function () {
  4916. var contexts = this.contexts;
  4917. this.contexts = new Map();
  4918. return contexts;
  4919. };
  4920. ChildrenOutletContexts.prototype.onOutletReAttached = function (contexts) { this.contexts = contexts; };
  4921. ChildrenOutletContexts.prototype.getOrCreateContext = function (childName) {
  4922. var context = this.getContext(childName);
  4923. if (!context) {
  4924. context = new OutletContext();
  4925. this.contexts.set(childName, context);
  4926. }
  4927. return context;
  4928. };
  4929. ChildrenOutletContexts.prototype.getContext = function (childName) { return this.contexts.get(childName) || null; };
  4930. return ChildrenOutletContexts;
  4931. }());
  4932. /**
  4933. * @license
  4934. * Copyright Google Inc. All Rights Reserved.
  4935. *
  4936. * Use of this source code is governed by an MIT-style license that can be
  4937. * found in the LICENSE file at https://angular.io/license
  4938. */
  4939. /**
  4940. * @description
  4941. *
  4942. * Acts as a placeholder that Angular dynamically fills based on the current router state.
  4943. *
  4944. * ```
  4945. * <router-outlet></router-outlet>
  4946. * <router-outlet name='left'></router-outlet>
  4947. * <router-outlet name='right'></router-outlet>
  4948. * ```
  4949. *
  4950. * A router outlet will emit an activate event any time a new component is being instantiated,
  4951. * and a deactivate event when it is being destroyed.
  4952. *
  4953. * ```
  4954. * <router-outlet
  4955. * (activate)='onActivate($event)'
  4956. * (deactivate)='onDeactivate($event)'></router-outlet>
  4957. * ```
  4958. * @ngModule RouterModule
  4959. *
  4960. * @publicApi
  4961. */
  4962. var RouterOutlet = /** @class */ (function () {
  4963. function RouterOutlet(parentContexts, location, resolver, name, changeDetector) {
  4964. this.parentContexts = parentContexts;
  4965. this.location = location;
  4966. this.resolver = resolver;
  4967. this.changeDetector = changeDetector;
  4968. this.activated = null;
  4969. this._activatedRoute = null;
  4970. this.activateEvents = new EventEmitter();
  4971. this.deactivateEvents = new EventEmitter();
  4972. this.name = name || PRIMARY_OUTLET;
  4973. parentContexts.onChildOutletCreated(this.name, this);
  4974. }
  4975. RouterOutlet.prototype.ngOnDestroy = function () { this.parentContexts.onChildOutletDestroyed(this.name); };
  4976. RouterOutlet.prototype.ngOnInit = function () {
  4977. if (!this.activated) {
  4978. // If the outlet was not instantiated at the time the route got activated we need to populate
  4979. // the outlet when it is initialized (ie inside a NgIf)
  4980. var context = this.parentContexts.getContext(this.name);
  4981. if (context && context.route) {
  4982. if (context.attachRef) {
  4983. // `attachRef` is populated when there is an existing component to mount
  4984. this.attach(context.attachRef, context.route);
  4985. }
  4986. else {
  4987. // otherwise the component defined in the configuration is created
  4988. this.activateWith(context.route, context.resolver || null);
  4989. }
  4990. }
  4991. }
  4992. };
  4993. Object.defineProperty(RouterOutlet.prototype, "isActivated", {
  4994. get: function () { return !!this.activated; },
  4995. enumerable: true,
  4996. configurable: true
  4997. });
  4998. Object.defineProperty(RouterOutlet.prototype, "component", {
  4999. get: function () {
  5000. if (!this.activated)
  5001. throw new Error('Outlet is not activated');
  5002. return this.activated.instance;
  5003. },
  5004. enumerable: true,
  5005. configurable: true
  5006. });
  5007. Object.defineProperty(RouterOutlet.prototype, "activatedRoute", {
  5008. get: function () {
  5009. if (!this.activated)
  5010. throw new Error('Outlet is not activated');
  5011. return this._activatedRoute;
  5012. },
  5013. enumerable: true,
  5014. configurable: true
  5015. });
  5016. Object.defineProperty(RouterOutlet.prototype, "activatedRouteData", {
  5017. get: function () {
  5018. if (this._activatedRoute) {
  5019. return this._activatedRoute.snapshot.data;
  5020. }
  5021. return {};
  5022. },
  5023. enumerable: true,
  5024. configurable: true
  5025. });
  5026. /**
  5027. * Called when the `RouteReuseStrategy` instructs to detach the subtree
  5028. */
  5029. RouterOutlet.prototype.detach = function () {
  5030. if (!this.activated)
  5031. throw new Error('Outlet is not activated');
  5032. this.location.detach();
  5033. var cmp = this.activated;
  5034. this.activated = null;
  5035. this._activatedRoute = null;
  5036. return cmp;
  5037. };
  5038. /**
  5039. * Called when the `RouteReuseStrategy` instructs to re-attach a previously detached subtree
  5040. */
  5041. RouterOutlet.prototype.attach = function (ref, activatedRoute) {
  5042. this.activated = ref;
  5043. this._activatedRoute = activatedRoute;
  5044. this.location.insert(ref.hostView);
  5045. };
  5046. RouterOutlet.prototype.deactivate = function () {
  5047. if (this.activated) {
  5048. var c = this.component;
  5049. this.activated.destroy();
  5050. this.activated = null;
  5051. this._activatedRoute = null;
  5052. this.deactivateEvents.emit(c);
  5053. }
  5054. };
  5055. RouterOutlet.prototype.activateWith = function (activatedRoute, resolver) {
  5056. if (this.isActivated) {
  5057. throw new Error('Cannot activate an already activated outlet');
  5058. }
  5059. this._activatedRoute = activatedRoute;
  5060. var snapshot = activatedRoute._futureSnapshot;
  5061. var component = snapshot.routeConfig.component;
  5062. resolver = resolver || this.resolver;
  5063. var factory = resolver.resolveComponentFactory(component);
  5064. var childContexts = this.parentContexts.getOrCreateContext(this.name).children;
  5065. var injector = new OutletInjector(activatedRoute, childContexts, this.location.injector);
  5066. this.activated = this.location.createComponent(factory, this.location.length, injector);
  5067. // Calling `markForCheck` to make sure we will run the change detection when the
  5068. // `RouterOutlet` is inside a `ChangeDetectionStrategy.OnPush` component.
  5069. this.changeDetector.markForCheck();
  5070. this.activateEvents.emit(this.activated.instance);
  5071. };
  5072. __decorate([
  5073. Output('activate'),
  5074. __metadata("design:type", Object)
  5075. ], RouterOutlet.prototype, "activateEvents", void 0);
  5076. __decorate([
  5077. Output('deactivate'),
  5078. __metadata("design:type", Object)
  5079. ], RouterOutlet.prototype, "deactivateEvents", void 0);
  5080. RouterOutlet = __decorate([
  5081. Directive({ selector: 'router-outlet', exportAs: 'outlet' }),
  5082. __param(3, Attribute('name')),
  5083. __metadata("design:paramtypes", [ChildrenOutletContexts, ViewContainerRef,
  5084. ComponentFactoryResolver, String, ChangeDetectorRef])
  5085. ], RouterOutlet);
  5086. return RouterOutlet;
  5087. }());
  5088. var OutletInjector = /** @class */ (function () {
  5089. function OutletInjector(route, childContexts, parent) {
  5090. this.route = route;
  5091. this.childContexts = childContexts;
  5092. this.parent = parent;
  5093. }
  5094. OutletInjector.prototype.get = function (token, notFoundValue) {
  5095. if (token === ActivatedRoute) {
  5096. return this.route;
  5097. }
  5098. if (token === ChildrenOutletContexts) {
  5099. return this.childContexts;
  5100. }
  5101. return this.parent.get(token, notFoundValue);
  5102. };
  5103. return OutletInjector;
  5104. }());
  5105. /**
  5106. *@license
  5107. *Copyright Google Inc. All Rights Reserved.
  5108. *
  5109. *Use of this source code is governed by an MIT-style license that can be
  5110. *found in the LICENSE file at https://angular.io/license
  5111. */
  5112. /**
  5113. * @description
  5114. *
  5115. * Provides a preloading strategy.
  5116. *
  5117. * @publicApi
  5118. */
  5119. var PreloadingStrategy = /** @class */ (function () {
  5120. function PreloadingStrategy() {
  5121. }
  5122. return PreloadingStrategy;
  5123. }());
  5124. /**
  5125. * @description
  5126. *
  5127. * Provides a preloading strategy that preloads all modules as quickly as possible.
  5128. *
  5129. * ```
  5130. * RouteModule.forRoot(ROUTES, {preloadingStrategy: PreloadAllModules})
  5131. * ```
  5132. *
  5133. * @publicApi
  5134. */
  5135. var PreloadAllModules = /** @class */ (function () {
  5136. function PreloadAllModules() {
  5137. }
  5138. PreloadAllModules.prototype.preload = function (route, fn) {
  5139. return fn().pipe(catchError(function () { return of(null); }));
  5140. };
  5141. return PreloadAllModules;
  5142. }());
  5143. /**
  5144. * @description
  5145. *
  5146. * Provides a preloading strategy that does not preload any modules.
  5147. *
  5148. * This strategy is enabled by default.
  5149. *
  5150. * @publicApi
  5151. */
  5152. var NoPreloading = /** @class */ (function () {
  5153. function NoPreloading() {
  5154. }
  5155. NoPreloading.prototype.preload = function (route, fn) { return of(null); };
  5156. return NoPreloading;
  5157. }());
  5158. /**
  5159. * The preloader optimistically loads all router configurations to
  5160. * make navigations into lazily-loaded sections of the application faster.
  5161. *
  5162. * The preloader runs in the background. When the router bootstraps, the preloader
  5163. * starts listening to all navigation events. After every such event, the preloader
  5164. * will check if any configurations can be loaded lazily.
  5165. *
  5166. * If a route is protected by `canLoad` guards, the preloaded will not load it.
  5167. *
  5168. * @publicApi
  5169. */
  5170. var RouterPreloader = /** @class */ (function () {
  5171. function RouterPreloader(router, moduleLoader, compiler, injector, preloadingStrategy) {
  5172. this.router = router;
  5173. this.injector = injector;
  5174. this.preloadingStrategy = preloadingStrategy;
  5175. var onStartLoad = function (r) { return router.triggerEvent(new RouteConfigLoadStart(r)); };
  5176. var onEndLoad = function (r) { return router.triggerEvent(new RouteConfigLoadEnd(r)); };
  5177. this.loader = new RouterConfigLoader(moduleLoader, compiler, onStartLoad, onEndLoad);
  5178. }
  5179. RouterPreloader.prototype.setUpPreloading = function () {
  5180. var _this = this;
  5181. this.subscription =
  5182. this.router.events
  5183. .pipe(filter(function (e) { return e instanceof NavigationEnd; }), concatMap(function () { return _this.preload(); }))
  5184. .subscribe(function () { });
  5185. };
  5186. RouterPreloader.prototype.preload = function () {
  5187. var ngModule = this.injector.get(NgModuleRef);
  5188. return this.processRoutes(ngModule, this.router.config);
  5189. };
  5190. // TODO(jasonaden): This class relies on code external to the class to call setUpPreloading. If
  5191. // this hasn't been done, ngOnDestroy will fail as this.subscription will be undefined. This
  5192. // should be refactored.
  5193. RouterPreloader.prototype.ngOnDestroy = function () { this.subscription.unsubscribe(); };
  5194. RouterPreloader.prototype.processRoutes = function (ngModule, routes) {
  5195. var e_1, _a;
  5196. var res = [];
  5197. try {
  5198. for (var routes_1 = __values(routes), routes_1_1 = routes_1.next(); !routes_1_1.done; routes_1_1 = routes_1.next()) {
  5199. var route = routes_1_1.value;
  5200. // we already have the config loaded, just recurse
  5201. if (route.loadChildren && !route.canLoad && route._loadedConfig) {
  5202. var childConfig = route._loadedConfig;
  5203. res.push(this.processRoutes(childConfig.module, childConfig.routes));
  5204. // no config loaded, fetch the config
  5205. }
  5206. else if (route.loadChildren && !route.canLoad) {
  5207. res.push(this.preloadConfig(ngModule, route));
  5208. // recurse into children
  5209. }
  5210. else if (route.children) {
  5211. res.push(this.processRoutes(ngModule, route.children));
  5212. }
  5213. }
  5214. }
  5215. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  5216. finally {
  5217. try {
  5218. if (routes_1_1 && !routes_1_1.done && (_a = routes_1.return)) _a.call(routes_1);
  5219. }
  5220. finally { if (e_1) throw e_1.error; }
  5221. }
  5222. return from(res).pipe(mergeAll(), map(function (_) { return void 0; }));
  5223. };
  5224. RouterPreloader.prototype.preloadConfig = function (ngModule, route) {
  5225. var _this = this;
  5226. return this.preloadingStrategy.preload(route, function () {
  5227. var loaded$ = _this.loader.load(ngModule.injector, route);
  5228. return loaded$.pipe(mergeMap(function (config) {
  5229. route._loadedConfig = config;
  5230. return _this.processRoutes(config.module, config.routes);
  5231. }));
  5232. });
  5233. };
  5234. RouterPreloader = __decorate([
  5235. Injectable(),
  5236. __metadata("design:paramtypes", [Router, NgModuleFactoryLoader, Compiler,
  5237. Injector, PreloadingStrategy])
  5238. ], RouterPreloader);
  5239. return RouterPreloader;
  5240. }());
  5241. /**
  5242. * @license
  5243. * Copyright Google Inc. All Rights Reserved.
  5244. *
  5245. * Use of this source code is governed by an MIT-style license that can be
  5246. * found in the LICENSE file at https://angular.io/license
  5247. */
  5248. var RouterScroller = /** @class */ (function () {
  5249. function RouterScroller(router,
  5250. /** @docsNotRequired */ viewportScroller, options) {
  5251. if (options === void 0) { options = {}; }
  5252. this.router = router;
  5253. this.viewportScroller = viewportScroller;
  5254. this.options = options;
  5255. this.lastId = 0;
  5256. this.lastSource = 'imperative';
  5257. this.restoredId = 0;
  5258. this.store = {};
  5259. // Default both options to 'disabled'
  5260. options.scrollPositionRestoration = options.scrollPositionRestoration || 'disabled';
  5261. options.anchorScrolling = options.anchorScrolling || 'disabled';
  5262. }
  5263. RouterScroller.prototype.init = function () {
  5264. // we want to disable the automatic scrolling because having two places
  5265. // responsible for scrolling results race conditions, especially given
  5266. // that browser don't implement this behavior consistently
  5267. if (this.options.scrollPositionRestoration !== 'disabled') {
  5268. this.viewportScroller.setHistoryScrollRestoration('manual');
  5269. }
  5270. this.routerEventsSubscription = this.createScrollEvents();
  5271. this.scrollEventsSubscription = this.consumeScrollEvents();
  5272. };
  5273. RouterScroller.prototype.createScrollEvents = function () {
  5274. var _this = this;
  5275. return this.router.events.subscribe(function (e) {
  5276. if (e instanceof NavigationStart) {
  5277. // store the scroll position of the current stable navigations.
  5278. _this.store[_this.lastId] = _this.viewportScroller.getScrollPosition();
  5279. _this.lastSource = e.navigationTrigger;
  5280. _this.restoredId = e.restoredState ? e.restoredState.navigationId : 0;
  5281. }
  5282. else if (e instanceof NavigationEnd) {
  5283. _this.lastId = e.id;
  5284. _this.scheduleScrollEvent(e, _this.router.parseUrl(e.urlAfterRedirects).fragment);
  5285. }
  5286. });
  5287. };
  5288. RouterScroller.prototype.consumeScrollEvents = function () {
  5289. var _this = this;
  5290. return this.router.events.subscribe(function (e) {
  5291. if (!(e instanceof Scroll))
  5292. return;
  5293. // a popstate event. The pop state event will always ignore anchor scrolling.
  5294. if (e.position) {
  5295. if (_this.options.scrollPositionRestoration === 'top') {
  5296. _this.viewportScroller.scrollToPosition([0, 0]);
  5297. }
  5298. else if (_this.options.scrollPositionRestoration === 'enabled') {
  5299. _this.viewportScroller.scrollToPosition(e.position);
  5300. }
  5301. // imperative navigation "forward"
  5302. }
  5303. else {
  5304. if (e.anchor && _this.options.anchorScrolling === 'enabled') {
  5305. _this.viewportScroller.scrollToAnchor(e.anchor);
  5306. }
  5307. else if (_this.options.scrollPositionRestoration !== 'disabled') {
  5308. _this.viewportScroller.scrollToPosition([0, 0]);
  5309. }
  5310. }
  5311. });
  5312. };
  5313. RouterScroller.prototype.scheduleScrollEvent = function (routerEvent, anchor) {
  5314. this.router.triggerEvent(new Scroll(routerEvent, this.lastSource === 'popstate' ? this.store[this.restoredId] : null, anchor));
  5315. };
  5316. RouterScroller.prototype.ngOnDestroy = function () {
  5317. if (this.routerEventsSubscription) {
  5318. this.routerEventsSubscription.unsubscribe();
  5319. }
  5320. if (this.scrollEventsSubscription) {
  5321. this.scrollEventsSubscription.unsubscribe();
  5322. }
  5323. };
  5324. return RouterScroller;
  5325. }());
  5326. /**
  5327. * @license
  5328. * Copyright Google Inc. All Rights Reserved.
  5329. *
  5330. * Use of this source code is governed by an MIT-style license that can be
  5331. * found in the LICENSE file at https://angular.io/license
  5332. */
  5333. /**
  5334. * @description
  5335. *
  5336. * Contains a list of directives
  5337. *
  5338. *
  5339. */
  5340. var ROUTER_DIRECTIVES = [RouterOutlet, RouterLink, RouterLinkWithHref, RouterLinkActive, ɵEmptyOutletComponent];
  5341. /**
  5342. * @description
  5343. *
  5344. * Is used in DI to configure the router.
  5345. *
  5346. * @publicApi
  5347. */
  5348. var ROUTER_CONFIGURATION = new InjectionToken('ROUTER_CONFIGURATION');
  5349. /**
  5350. * @docsNotRequired
  5351. */
  5352. var ROUTER_FORROOT_GUARD = new InjectionToken('ROUTER_FORROOT_GUARD');
  5353. var ɵ0 = { enableTracing: false };
  5354. var ROUTER_PROVIDERS = [
  5355. Location,
  5356. { provide: UrlSerializer, useClass: DefaultUrlSerializer },
  5357. {
  5358. provide: Router,
  5359. useFactory: setupRouter,
  5360. deps: [
  5361. ApplicationRef, UrlSerializer, ChildrenOutletContexts, Location, Injector,
  5362. NgModuleFactoryLoader, Compiler, ROUTES, ROUTER_CONFIGURATION,
  5363. [UrlHandlingStrategy, new Optional()], [RouteReuseStrategy, new Optional()]
  5364. ]
  5365. },
  5366. ChildrenOutletContexts,
  5367. { provide: ActivatedRoute, useFactory: rootRoute, deps: [Router] },
  5368. { provide: NgModuleFactoryLoader, useClass: SystemJsNgModuleLoader },
  5369. RouterPreloader,
  5370. NoPreloading,
  5371. PreloadAllModules,
  5372. { provide: ROUTER_CONFIGURATION, useValue: ɵ0 },
  5373. ];
  5374. function routerNgProbeToken() {
  5375. return new NgProbeToken('Router', Router);
  5376. }
  5377. /**
  5378. * @usageNotes
  5379. *
  5380. * RouterModule can be imported multiple times: once per lazily-loaded bundle.
  5381. * Since the router deals with a global shared resource--location, we cannot have
  5382. * more than one router service active.
  5383. *
  5384. * That is why there are two ways to create the module: `RouterModule.forRoot` and
  5385. * `RouterModule.forChild`.
  5386. *
  5387. * * `forRoot` creates a module that contains all the directives, the given routes, and the router
  5388. * service itself.
  5389. * * `forChild` creates a module that contains all the directives and the given routes, but does not
  5390. * include the router service.
  5391. *
  5392. * When registered at the root, the module should be used as follows
  5393. *
  5394. * ```
  5395. * @NgModule({
  5396. * imports: [RouterModule.forRoot(ROUTES)]
  5397. * })
  5398. * class MyNgModule {}
  5399. * ```
  5400. *
  5401. * For submodules and lazy loaded submodules the module should be used as follows:
  5402. *
  5403. * ```
  5404. * @NgModule({
  5405. * imports: [RouterModule.forChild(ROUTES)]
  5406. * })
  5407. * class MyNgModule {}
  5408. * ```
  5409. *
  5410. * @description
  5411. *
  5412. * Adds router directives and providers.
  5413. *
  5414. * Managing state transitions is one of the hardest parts of building applications. This is
  5415. * especially true on the web, where you also need to ensure that the state is reflected in the URL.
  5416. * In addition, we often want to split applications into multiple bundles and load them on demand.
  5417. * Doing this transparently is not trivial.
  5418. *
  5419. * The Angular router solves these problems. Using the router, you can declaratively specify
  5420. * application states, manage state transitions while taking care of the URL, and load bundles on
  5421. * demand.
  5422. *
  5423. * [Read this developer guide](https://angular.io/docs/ts/latest/guide/router.html) to get an
  5424. * overview of how the router should be used.
  5425. *
  5426. * @publicApi
  5427. */
  5428. var RouterModule = /** @class */ (function () {
  5429. // Note: We are injecting the Router so it gets created eagerly...
  5430. function RouterModule(guard, router) {
  5431. }
  5432. RouterModule_1 = RouterModule;
  5433. /**
  5434. * Creates a module with all the router providers and directives. It also optionally sets up an
  5435. * application listener to perform an initial navigation.
  5436. *
  5437. * Configuration Options:
  5438. *
  5439. * * `enableTracing` Toggles whether the router should log all navigation events to the console.
  5440. * * `useHash` Enables the location strategy that uses the URL fragment instead of the history
  5441. * API.
  5442. * * `initialNavigation` Disables the initial navigation.
  5443. * * `errorHandler` Defines a custom error handler for failed navigations.
  5444. * * `preloadingStrategy` Configures a preloading strategy. See `PreloadAllModules`.
  5445. * * `onSameUrlNavigation` Define what the router should do if it receives a navigation request to
  5446. * the current URL.
  5447. * * `scrollPositionRestoration` Configures if the scroll position needs to be restored when
  5448. * navigating back.
  5449. * * `anchorScrolling` Configures if the router should scroll to the element when the url has a
  5450. * fragment.
  5451. * * `scrollOffset` Configures the scroll offset the router will use when scrolling to an element.
  5452. * * `paramsInheritanceStrategy` Defines how the router merges params, data and resolved data from
  5453. * parent to child routes.
  5454. * * `malformedUriErrorHandler` Defines a custom malformed uri error handler function. This
  5455. * handler is invoked when encodedURI contains invalid character sequences.
  5456. * * `urlUpdateStrategy` Defines when the router updates the browser URL. The default behavior is
  5457. * to update after successful navigation.
  5458. * * `relativeLinkResolution` Enables the correct relative link resolution in components with
  5459. * empty paths.
  5460. *
  5461. * See `ExtraOptions` for more details about the above options.
  5462. */
  5463. RouterModule.forRoot = function (routes, config) {
  5464. return {
  5465. ngModule: RouterModule_1,
  5466. providers: [
  5467. ROUTER_PROVIDERS,
  5468. provideRoutes(routes),
  5469. {
  5470. provide: ROUTER_FORROOT_GUARD,
  5471. useFactory: provideForRootGuard,
  5472. deps: [[Router, new Optional(), new SkipSelf()]]
  5473. },
  5474. { provide: ROUTER_CONFIGURATION, useValue: config ? config : {} },
  5475. {
  5476. provide: LocationStrategy,
  5477. useFactory: provideLocationStrategy,
  5478. deps: [
  5479. PlatformLocation, [new Inject(APP_BASE_HREF), new Optional()], ROUTER_CONFIGURATION
  5480. ]
  5481. },
  5482. {
  5483. provide: RouterScroller,
  5484. useFactory: createRouterScroller,
  5485. deps: [Router, ViewportScroller, ROUTER_CONFIGURATION]
  5486. },
  5487. {
  5488. provide: PreloadingStrategy,
  5489. useExisting: config && config.preloadingStrategy ? config.preloadingStrategy :
  5490. NoPreloading
  5491. },
  5492. { provide: NgProbeToken, multi: true, useFactory: routerNgProbeToken },
  5493. provideRouterInitializer(),
  5494. ],
  5495. };
  5496. };
  5497. /**
  5498. * Creates a module with all the router directives and a provider registering routes.
  5499. */
  5500. RouterModule.forChild = function (routes) {
  5501. return { ngModule: RouterModule_1, providers: [provideRoutes(routes)] };
  5502. };
  5503. var RouterModule_1;
  5504. RouterModule = RouterModule_1 = __decorate([
  5505. NgModule({
  5506. declarations: ROUTER_DIRECTIVES,
  5507. exports: ROUTER_DIRECTIVES,
  5508. entryComponents: [ɵEmptyOutletComponent]
  5509. }),
  5510. __param(0, Optional()), __param(0, Inject(ROUTER_FORROOT_GUARD)), __param(1, Optional()),
  5511. __metadata("design:paramtypes", [Object, Router])
  5512. ], RouterModule);
  5513. return RouterModule;
  5514. }());
  5515. function createRouterScroller(router, viewportScroller, config) {
  5516. if (config.scrollOffset) {
  5517. viewportScroller.setOffset(config.scrollOffset);
  5518. }
  5519. return new RouterScroller(router, viewportScroller, config);
  5520. }
  5521. function provideLocationStrategy(platformLocationStrategy, baseHref, options) {
  5522. if (options === void 0) { options = {}; }
  5523. return options.useHash ? new HashLocationStrategy(platformLocationStrategy, baseHref) :
  5524. new PathLocationStrategy(platformLocationStrategy, baseHref);
  5525. }
  5526. function provideForRootGuard(router) {
  5527. if (router) {
  5528. throw new Error("RouterModule.forRoot() called twice. Lazy loaded modules should use RouterModule.forChild() instead.");
  5529. }
  5530. return 'guarded';
  5531. }
  5532. /**
  5533. * @description
  5534. *
  5535. * Registers routes.
  5536. *
  5537. * @usageNotes
  5538. * ### Example
  5539. *
  5540. * ```
  5541. * @NgModule({
  5542. * imports: [RouterModule.forChild(ROUTES)],
  5543. * providers: [provideRoutes(EXTRA_ROUTES)]
  5544. * })
  5545. * class MyNgModule {}
  5546. * ```
  5547. *
  5548. * @publicApi
  5549. */
  5550. function provideRoutes(routes) {
  5551. return [
  5552. { provide: ANALYZE_FOR_ENTRY_COMPONENTS, multi: true, useValue: routes },
  5553. { provide: ROUTES, multi: true, useValue: routes },
  5554. ];
  5555. }
  5556. function setupRouter(ref, urlSerializer, contexts, location, injector, loader, compiler, config, opts, urlHandlingStrategy, routeReuseStrategy) {
  5557. if (opts === void 0) { opts = {}; }
  5558. var router = new Router(null, urlSerializer, contexts, location, injector, loader, compiler, flatten(config));
  5559. if (urlHandlingStrategy) {
  5560. router.urlHandlingStrategy = urlHandlingStrategy;
  5561. }
  5562. if (routeReuseStrategy) {
  5563. router.routeReuseStrategy = routeReuseStrategy;
  5564. }
  5565. if (opts.errorHandler) {
  5566. router.errorHandler = opts.errorHandler;
  5567. }
  5568. if (opts.malformedUriErrorHandler) {
  5569. router.malformedUriErrorHandler = opts.malformedUriErrorHandler;
  5570. }
  5571. if (opts.enableTracing) {
  5572. var dom_1 = ɵgetDOM();
  5573. router.events.subscribe(function (e) {
  5574. dom_1.logGroup("Router Event: " + e.constructor.name);
  5575. dom_1.log(e.toString());
  5576. dom_1.log(e);
  5577. dom_1.logGroupEnd();
  5578. });
  5579. }
  5580. if (opts.onSameUrlNavigation) {
  5581. router.onSameUrlNavigation = opts.onSameUrlNavigation;
  5582. }
  5583. if (opts.paramsInheritanceStrategy) {
  5584. router.paramsInheritanceStrategy = opts.paramsInheritanceStrategy;
  5585. }
  5586. if (opts.urlUpdateStrategy) {
  5587. router.urlUpdateStrategy = opts.urlUpdateStrategy;
  5588. }
  5589. if (opts.relativeLinkResolution) {
  5590. router.relativeLinkResolution = opts.relativeLinkResolution;
  5591. }
  5592. return router;
  5593. }
  5594. function rootRoute(router) {
  5595. return router.routerState.root;
  5596. }
  5597. /**
  5598. * To initialize the router properly we need to do in two steps:
  5599. *
  5600. * We need to start the navigation in a APP_INITIALIZER to block the bootstrap if
  5601. * a resolver or a guards executes asynchronously. Second, we need to actually run
  5602. * activation in a BOOTSTRAP_LISTENER. We utilize the afterPreactivation
  5603. * hook provided by the router to do that.
  5604. *
  5605. * The router navigation starts, reaches the point when preactivation is done, and then
  5606. * pauses. It waits for the hook to be resolved. We then resolve it only in a bootstrap listener.
  5607. */
  5608. var RouterInitializer = /** @class */ (function () {
  5609. function RouterInitializer(injector) {
  5610. this.injector = injector;
  5611. this.initNavigation = false;
  5612. this.resultOfPreactivationDone = new Subject();
  5613. }
  5614. RouterInitializer.prototype.appInitializer = function () {
  5615. var _this = this;
  5616. var p = this.injector.get(LOCATION_INITIALIZED, Promise.resolve(null));
  5617. return p.then(function () {
  5618. var resolve = null;
  5619. var res = new Promise(function (r) { return resolve = r; });
  5620. var router = _this.injector.get(Router);
  5621. var opts = _this.injector.get(ROUTER_CONFIGURATION);
  5622. if (_this.isLegacyDisabled(opts) || _this.isLegacyEnabled(opts)) {
  5623. resolve(true);
  5624. }
  5625. else if (opts.initialNavigation === 'disabled') {
  5626. router.setUpLocationChangeListener();
  5627. resolve(true);
  5628. }
  5629. else if (opts.initialNavigation === 'enabled') {
  5630. router.hooks.afterPreactivation = function () {
  5631. // only the initial navigation should be delayed
  5632. if (!_this.initNavigation) {
  5633. _this.initNavigation = true;
  5634. resolve(true);
  5635. return _this.resultOfPreactivationDone;
  5636. // subsequent navigations should not be delayed
  5637. }
  5638. else {
  5639. return of(null);
  5640. }
  5641. };
  5642. router.initialNavigation();
  5643. }
  5644. else {
  5645. throw new Error("Invalid initialNavigation options: '" + opts.initialNavigation + "'");
  5646. }
  5647. return res;
  5648. });
  5649. };
  5650. RouterInitializer.prototype.bootstrapListener = function (bootstrappedComponentRef) {
  5651. var opts = this.injector.get(ROUTER_CONFIGURATION);
  5652. var preloader = this.injector.get(RouterPreloader);
  5653. var routerScroller = this.injector.get(RouterScroller);
  5654. var router = this.injector.get(Router);
  5655. var ref = this.injector.get(ApplicationRef);
  5656. if (bootstrappedComponentRef !== ref.components[0]) {
  5657. return;
  5658. }
  5659. if (this.isLegacyEnabled(opts)) {
  5660. router.initialNavigation();
  5661. }
  5662. else if (this.isLegacyDisabled(opts)) {
  5663. router.setUpLocationChangeListener();
  5664. }
  5665. preloader.setUpPreloading();
  5666. routerScroller.init();
  5667. router.resetRootComponentType(ref.componentTypes[0]);
  5668. this.resultOfPreactivationDone.next(null);
  5669. this.resultOfPreactivationDone.complete();
  5670. };
  5671. RouterInitializer.prototype.isLegacyEnabled = function (opts) {
  5672. return opts.initialNavigation === 'legacy_enabled' || opts.initialNavigation === true ||
  5673. opts.initialNavigation === undefined;
  5674. };
  5675. RouterInitializer.prototype.isLegacyDisabled = function (opts) {
  5676. return opts.initialNavigation === 'legacy_disabled' || opts.initialNavigation === false;
  5677. };
  5678. RouterInitializer = __decorate([
  5679. Injectable(),
  5680. __metadata("design:paramtypes", [Injector])
  5681. ], RouterInitializer);
  5682. return RouterInitializer;
  5683. }());
  5684. function getAppInitializer(r) {
  5685. return r.appInitializer.bind(r);
  5686. }
  5687. function getBootstrapListener(r) {
  5688. return r.bootstrapListener.bind(r);
  5689. }
  5690. /**
  5691. * A token for the router initializer that will be called after the app is bootstrapped.
  5692. *
  5693. * @publicApi
  5694. */
  5695. var ROUTER_INITIALIZER = new InjectionToken('Router Initializer');
  5696. function provideRouterInitializer() {
  5697. return [
  5698. RouterInitializer,
  5699. {
  5700. provide: APP_INITIALIZER,
  5701. multi: true,
  5702. useFactory: getAppInitializer,
  5703. deps: [RouterInitializer]
  5704. },
  5705. { provide: ROUTER_INITIALIZER, useFactory: getBootstrapListener, deps: [RouterInitializer] },
  5706. { provide: APP_BOOTSTRAP_LISTENER, multi: true, useExisting: ROUTER_INITIALIZER },
  5707. ];
  5708. }
  5709. /**
  5710. * @license
  5711. * Copyright Google Inc. All Rights Reserved.
  5712. *
  5713. * Use of this source code is governed by an MIT-style license that can be
  5714. * found in the LICENSE file at https://angular.io/license
  5715. */
  5716. /**
  5717. * @publicApi
  5718. */
  5719. var VERSION = new Version('8.1.0');
  5720. /**
  5721. * @license
  5722. * Copyright Google Inc. All Rights Reserved.
  5723. *
  5724. * Use of this source code is governed by an MIT-style license that can be
  5725. * found in the LICENSE file at https://angular.io/license
  5726. */
  5727. /**
  5728. * @license
  5729. * Copyright Google Inc. All Rights Reserved.
  5730. *
  5731. * Use of this source code is governed by an MIT-style license that can be
  5732. * found in the LICENSE file at https://angular.io/license
  5733. */
  5734. /**
  5735. * @license
  5736. * Copyright Google Inc. All Rights Reserved.
  5737. *
  5738. * Use of this source code is governed by an MIT-style license that can be
  5739. * found in the LICENSE file at https://angular.io/license
  5740. */
  5741. // This file only reexports content of the `src` folder. Keep it that way.
  5742. /**
  5743. * @license
  5744. * Copyright Google Inc. All Rights Reserved.
  5745. *
  5746. * Use of this source code is governed by an MIT-style license that can be
  5747. * found in the LICENSE file at https://angular.io/license
  5748. */
  5749. /**
  5750. * Generated bundle index. Do not edit.
  5751. */
  5752. export { ɵEmptyOutletComponent as ɵangular_packages_router_router_l, ɵEmptyOutletComponent, ROUTER_FORROOT_GUARD as ɵangular_packages_router_router_a, RouterInitializer as ɵangular_packages_router_router_h, createRouterScroller as ɵangular_packages_router_router_c, getAppInitializer as ɵangular_packages_router_router_i, getBootstrapListener as ɵangular_packages_router_router_j, provideForRootGuard as ɵangular_packages_router_router_e, provideLocationStrategy as ɵangular_packages_router_router_d, provideRouterInitializer as ɵangular_packages_router_router_k, rootRoute as ɵangular_packages_router_router_g, routerNgProbeToken as ɵangular_packages_router_router_b, setupRouter as ɵangular_packages_router_router_f, RouterScroller as ɵangular_packages_router_router_o, Tree as ɵangular_packages_router_router_m, TreeNode as ɵangular_packages_router_router_n, RouterLink, RouterLinkWithHref, RouterLinkActive, RouterOutlet, ActivationEnd, ActivationStart, ChildActivationEnd, ChildActivationStart, GuardsCheckEnd, GuardsCheckStart, NavigationCancel, NavigationEnd, NavigationError, NavigationStart, ResolveEnd, ResolveStart, RouteConfigLoadEnd, RouteConfigLoadStart, RouterEvent, RoutesRecognized, Scroll, RouteReuseStrategy, Router, ROUTES, ROUTER_CONFIGURATION, ROUTER_INITIALIZER, RouterModule, provideRoutes, ChildrenOutletContexts, OutletContext, NoPreloading, PreloadAllModules, PreloadingStrategy, RouterPreloader, ActivatedRoute, ActivatedRouteSnapshot, RouterState, RouterStateSnapshot, PRIMARY_OUTLET, convertToParamMap, UrlHandlingStrategy, DefaultUrlSerializer, UrlSegment, UrlSegmentGroup, UrlSerializer, UrlTree, VERSION, ROUTER_PROVIDERS as ɵROUTER_PROVIDERS, flatten as ɵflatten };
  5753. //# sourceMappingURL=router.js.map