router.mjs 285 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981
  1. /**
  2. * @license Angular v16.0.4
  3. * (c) 2010-2022 Google LLC. https://angular.io/
  4. * License: MIT
  5. */
  6. import * as i0 from '@angular/core';
  7. import { ɵisPromise, ɵRuntimeError, Injectable, EventEmitter, inject, ViewContainerRef, ChangeDetectorRef, EnvironmentInjector, Directive, Input, Output, InjectionToken, reflectComponentType, Component, createEnvironmentInjector, ɵisNgModule, isStandalone, ɵisInjectable, Compiler, InjectFlags, NgModuleFactory, ɵConsole, ɵInitialRenderPendingTasks, NgZone, ɵcoerceToBoolean, ɵɵsanitizeUrlOrResourceUrl, Attribute, HostBinding, HostListener, Optional, ContentChildren, makeEnvironmentProviders, APP_BOOTSTRAP_LISTENER, ENVIRONMENT_INITIALIZER, Injector, ApplicationRef, APP_INITIALIZER, NgProbeToken, SkipSelf, NgModule, Inject, Version } from '@angular/core';
  8. import { isObservable, from, of, BehaviorSubject, combineLatest, EmptyError, concat, defer, pipe, throwError, EMPTY, ConnectableObservable, Subject } from 'rxjs';
  9. import * as i3 from '@angular/common';
  10. import { Location, ViewportScroller, LOCATION_INITIALIZED, LocationStrategy, HashLocationStrategy, PathLocationStrategy } from '@angular/common';
  11. import { map, switchMap, take, startWith, filter, mergeMap, first, concatMap, tap, catchError, scan, defaultIfEmpty, last as last$1, takeLast, mapTo, finalize, refCount, mergeAll } from 'rxjs/operators';
  12. import * as i1 from '@angular/platform-browser';
  13. /**
  14. * The primary routing outlet.
  15. *
  16. * @publicApi
  17. */
  18. const PRIMARY_OUTLET = 'primary';
  19. /**
  20. * A private symbol used to store the value of `Route.title` inside the `Route.data` if it is a
  21. * static string or `Route.resolve` if anything else. This allows us to reuse the existing route
  22. * data/resolvers to support the title feature without new instrumentation in the `Router` pipeline.
  23. */
  24. const RouteTitleKey = Symbol('RouteTitle');
  25. class ParamsAsMap {
  26. constructor(params) {
  27. this.params = params || {};
  28. }
  29. has(name) {
  30. return Object.prototype.hasOwnProperty.call(this.params, name);
  31. }
  32. get(name) {
  33. if (this.has(name)) {
  34. const v = this.params[name];
  35. return Array.isArray(v) ? v[0] : v;
  36. }
  37. return null;
  38. }
  39. getAll(name) {
  40. if (this.has(name)) {
  41. const v = this.params[name];
  42. return Array.isArray(v) ? v : [v];
  43. }
  44. return [];
  45. }
  46. get keys() {
  47. return Object.keys(this.params);
  48. }
  49. }
  50. /**
  51. * Converts a `Params` instance to a `ParamMap`.
  52. * @param params The instance to convert.
  53. * @returns The new map instance.
  54. *
  55. * @publicApi
  56. */
  57. function convertToParamMap(params) {
  58. return new ParamsAsMap(params);
  59. }
  60. /**
  61. * Matches the route configuration (`route`) against the actual URL (`segments`).
  62. *
  63. * When no matcher is defined on a `Route`, this is the matcher used by the Router by default.
  64. *
  65. * @param segments The remaining unmatched segments in the current navigation
  66. * @param segmentGroup The current segment group being matched
  67. * @param route The `Route` to match against.
  68. *
  69. * @see UrlMatchResult
  70. * @see Route
  71. *
  72. * @returns The resulting match information or `null` if the `route` should not match.
  73. * @publicApi
  74. */
  75. function defaultUrlMatcher(segments, segmentGroup, route) {
  76. const parts = route.path.split('/');
  77. if (parts.length > segments.length) {
  78. // The actual URL is shorter than the config, no match
  79. return null;
  80. }
  81. if (route.pathMatch === 'full' &&
  82. (segmentGroup.hasChildren() || parts.length < segments.length)) {
  83. // The config is longer than the actual URL but we are looking for a full match, return null
  84. return null;
  85. }
  86. const posParams = {};
  87. // Check each config part against the actual URL
  88. for (let index = 0; index < parts.length; index++) {
  89. const part = parts[index];
  90. const segment = segments[index];
  91. const isParameter = part.startsWith(':');
  92. if (isParameter) {
  93. posParams[part.substring(1)] = segment;
  94. }
  95. else if (part !== segment.path) {
  96. // The actual URL part does not match the config, no match
  97. return null;
  98. }
  99. }
  100. return { consumed: segments.slice(0, parts.length), posParams };
  101. }
  102. function shallowEqualArrays(a, b) {
  103. if (a.length !== b.length)
  104. return false;
  105. for (let i = 0; i < a.length; ++i) {
  106. if (!shallowEqual(a[i], b[i]))
  107. return false;
  108. }
  109. return true;
  110. }
  111. function shallowEqual(a, b) {
  112. // While `undefined` should never be possible, it would sometimes be the case in IE 11
  113. // and pre-chromium Edge. The check below accounts for this edge case.
  114. const k1 = a ? Object.keys(a) : undefined;
  115. const k2 = b ? Object.keys(b) : undefined;
  116. if (!k1 || !k2 || k1.length != k2.length) {
  117. return false;
  118. }
  119. let key;
  120. for (let i = 0; i < k1.length; i++) {
  121. key = k1[i];
  122. if (!equalArraysOrString(a[key], b[key])) {
  123. return false;
  124. }
  125. }
  126. return true;
  127. }
  128. /**
  129. * Test equality for arrays of strings or a string.
  130. */
  131. function equalArraysOrString(a, b) {
  132. if (Array.isArray(a) && Array.isArray(b)) {
  133. if (a.length !== b.length)
  134. return false;
  135. const aSorted = [...a].sort();
  136. const bSorted = [...b].sort();
  137. return aSorted.every((val, index) => bSorted[index] === val);
  138. }
  139. else {
  140. return a === b;
  141. }
  142. }
  143. /**
  144. * Return the last element of an array.
  145. */
  146. function last(a) {
  147. return a.length > 0 ? a[a.length - 1] : null;
  148. }
  149. function wrapIntoObservable(value) {
  150. if (isObservable(value)) {
  151. return value;
  152. }
  153. if (ɵisPromise(value)) {
  154. // Use `Promise.resolve()` to wrap promise-like instances.
  155. // Required ie when a Resolver returns a AngularJS `$q` promise to correctly trigger the
  156. // change detection.
  157. return from(Promise.resolve(value));
  158. }
  159. return of(value);
  160. }
  161. const pathCompareMap = {
  162. 'exact': equalSegmentGroups,
  163. 'subset': containsSegmentGroup,
  164. };
  165. const paramCompareMap = {
  166. 'exact': equalParams,
  167. 'subset': containsParams,
  168. 'ignored': () => true,
  169. };
  170. function containsTree(container, containee, options) {
  171. return pathCompareMap[options.paths](container.root, containee.root, options.matrixParams) &&
  172. paramCompareMap[options.queryParams](container.queryParams, containee.queryParams) &&
  173. !(options.fragment === 'exact' && container.fragment !== containee.fragment);
  174. }
  175. function equalParams(container, containee) {
  176. // TODO: This does not handle array params correctly.
  177. return shallowEqual(container, containee);
  178. }
  179. function equalSegmentGroups(container, containee, matrixParams) {
  180. if (!equalPath(container.segments, containee.segments))
  181. return false;
  182. if (!matrixParamsMatch(container.segments, containee.segments, matrixParams)) {
  183. return false;
  184. }
  185. if (container.numberOfChildren !== containee.numberOfChildren)
  186. return false;
  187. for (const c in containee.children) {
  188. if (!container.children[c])
  189. return false;
  190. if (!equalSegmentGroups(container.children[c], containee.children[c], matrixParams))
  191. return false;
  192. }
  193. return true;
  194. }
  195. function containsParams(container, containee) {
  196. return Object.keys(containee).length <= Object.keys(container).length &&
  197. Object.keys(containee).every(key => equalArraysOrString(container[key], containee[key]));
  198. }
  199. function containsSegmentGroup(container, containee, matrixParams) {
  200. return containsSegmentGroupHelper(container, containee, containee.segments, matrixParams);
  201. }
  202. function containsSegmentGroupHelper(container, containee, containeePaths, matrixParams) {
  203. if (container.segments.length > containeePaths.length) {
  204. const current = container.segments.slice(0, containeePaths.length);
  205. if (!equalPath(current, containeePaths))
  206. return false;
  207. if (containee.hasChildren())
  208. return false;
  209. if (!matrixParamsMatch(current, containeePaths, matrixParams))
  210. return false;
  211. return true;
  212. }
  213. else if (container.segments.length === containeePaths.length) {
  214. if (!equalPath(container.segments, containeePaths))
  215. return false;
  216. if (!matrixParamsMatch(container.segments, containeePaths, matrixParams))
  217. return false;
  218. for (const c in containee.children) {
  219. if (!container.children[c])
  220. return false;
  221. if (!containsSegmentGroup(container.children[c], containee.children[c], matrixParams)) {
  222. return false;
  223. }
  224. }
  225. return true;
  226. }
  227. else {
  228. const current = containeePaths.slice(0, container.segments.length);
  229. const next = containeePaths.slice(container.segments.length);
  230. if (!equalPath(container.segments, current))
  231. return false;
  232. if (!matrixParamsMatch(container.segments, current, matrixParams))
  233. return false;
  234. if (!container.children[PRIMARY_OUTLET])
  235. return false;
  236. return containsSegmentGroupHelper(container.children[PRIMARY_OUTLET], containee, next, matrixParams);
  237. }
  238. }
  239. function matrixParamsMatch(containerPaths, containeePaths, options) {
  240. return containeePaths.every((containeeSegment, i) => {
  241. return paramCompareMap[options](containerPaths[i].parameters, containeeSegment.parameters);
  242. });
  243. }
  244. /**
  245. * @description
  246. *
  247. * Represents the parsed URL.
  248. *
  249. * Since a router state is a tree, and the URL is nothing but a serialized state, the URL is a
  250. * serialized tree.
  251. * UrlTree is a data structure that provides a lot of affordances in dealing with URLs
  252. *
  253. * @usageNotes
  254. * ### Example
  255. *
  256. * ```
  257. * @Component({templateUrl:'template.html'})
  258. * class MyComponent {
  259. * constructor(router: Router) {
  260. * const tree: UrlTree =
  261. * router.parseUrl('/team/33/(user/victor//support:help)?debug=true#fragment');
  262. * const f = tree.fragment; // return 'fragment'
  263. * const q = tree.queryParams; // returns {debug: 'true'}
  264. * const g: UrlSegmentGroup = tree.root.children[PRIMARY_OUTLET];
  265. * const s: UrlSegment[] = g.segments; // returns 2 segments 'team' and '33'
  266. * g.children[PRIMARY_OUTLET].segments; // returns 2 segments 'user' and 'victor'
  267. * g.children['support'].segments; // return 1 segment 'help'
  268. * }
  269. * }
  270. * ```
  271. *
  272. * @publicApi
  273. */
  274. class UrlTree {
  275. constructor(
  276. /** The root segment group of the URL tree */
  277. root = new UrlSegmentGroup([], {}),
  278. /** The query params of the URL */
  279. queryParams = {},
  280. /** The fragment of the URL */
  281. fragment = null) {
  282. this.root = root;
  283. this.queryParams = queryParams;
  284. this.fragment = fragment;
  285. if (typeof ngDevMode === 'undefined' || ngDevMode) {
  286. if (root.segments.length > 0) {
  287. throw new ɵRuntimeError(4015 /* RuntimeErrorCode.INVALID_ROOT_URL_SEGMENT */, 'The root `UrlSegmentGroup` should not contain `segments`. ' +
  288. 'Instead, these segments belong in the `children` so they can be associated with a named outlet.');
  289. }
  290. }
  291. }
  292. get queryParamMap() {
  293. if (!this._queryParamMap) {
  294. this._queryParamMap = convertToParamMap(this.queryParams);
  295. }
  296. return this._queryParamMap;
  297. }
  298. /** @docsNotRequired */
  299. toString() {
  300. return DEFAULT_SERIALIZER.serialize(this);
  301. }
  302. }
  303. /**
  304. * @description
  305. *
  306. * Represents the parsed URL segment group.
  307. *
  308. * See `UrlTree` for more information.
  309. *
  310. * @publicApi
  311. */
  312. class UrlSegmentGroup {
  313. constructor(
  314. /** The URL segments of this group. See `UrlSegment` for more information */
  315. segments,
  316. /** The list of children of this group */
  317. children) {
  318. this.segments = segments;
  319. this.children = children;
  320. /** The parent node in the url tree */
  321. this.parent = null;
  322. Object.values(children).forEach((v) => (v.parent = this));
  323. }
  324. /** Whether the segment has child segments */
  325. hasChildren() {
  326. return this.numberOfChildren > 0;
  327. }
  328. /** Number of child segments */
  329. get numberOfChildren() {
  330. return Object.keys(this.children).length;
  331. }
  332. /** @docsNotRequired */
  333. toString() {
  334. return serializePaths(this);
  335. }
  336. }
  337. /**
  338. * @description
  339. *
  340. * Represents a single URL segment.
  341. *
  342. * A UrlSegment is a part of a URL between the two slashes. It contains a path and the matrix
  343. * parameters associated with the segment.
  344. *
  345. * @usageNotes
  346. * ### Example
  347. *
  348. * ```
  349. * @Component({templateUrl:'template.html'})
  350. * class MyComponent {
  351. * constructor(router: Router) {
  352. * const tree: UrlTree = router.parseUrl('/team;id=33');
  353. * const g: UrlSegmentGroup = tree.root.children[PRIMARY_OUTLET];
  354. * const s: UrlSegment[] = g.segments;
  355. * s[0].path; // returns 'team'
  356. * s[0].parameters; // returns {id: 33}
  357. * }
  358. * }
  359. * ```
  360. *
  361. * @publicApi
  362. */
  363. class UrlSegment {
  364. constructor(
  365. /** The path part of a URL segment */
  366. path,
  367. /** The matrix parameters associated with a segment */
  368. parameters) {
  369. this.path = path;
  370. this.parameters = parameters;
  371. }
  372. get parameterMap() {
  373. if (!this._parameterMap) {
  374. this._parameterMap = convertToParamMap(this.parameters);
  375. }
  376. return this._parameterMap;
  377. }
  378. /** @docsNotRequired */
  379. toString() {
  380. return serializePath(this);
  381. }
  382. }
  383. function equalSegments(as, bs) {
  384. return equalPath(as, bs) && as.every((a, i) => shallowEqual(a.parameters, bs[i].parameters));
  385. }
  386. function equalPath(as, bs) {
  387. if (as.length !== bs.length)
  388. return false;
  389. return as.every((a, i) => a.path === bs[i].path);
  390. }
  391. function mapChildrenIntoArray(segment, fn) {
  392. let res = [];
  393. Object.entries(segment.children).forEach(([childOutlet, child]) => {
  394. if (childOutlet === PRIMARY_OUTLET) {
  395. res = res.concat(fn(child, childOutlet));
  396. }
  397. });
  398. Object.entries(segment.children).forEach(([childOutlet, child]) => {
  399. if (childOutlet !== PRIMARY_OUTLET) {
  400. res = res.concat(fn(child, childOutlet));
  401. }
  402. });
  403. return res;
  404. }
  405. /**
  406. * @description
  407. *
  408. * Serializes and deserializes a URL string into a URL tree.
  409. *
  410. * The url serialization strategy is customizable. You can
  411. * make all URLs case insensitive by providing a custom UrlSerializer.
  412. *
  413. * See `DefaultUrlSerializer` for an example of a URL serializer.
  414. *
  415. * @publicApi
  416. */
  417. class UrlSerializer {
  418. static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "16.0.4", ngImport: i0, type: UrlSerializer, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
  419. static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "16.0.4", ngImport: i0, type: UrlSerializer, providedIn: 'root', useFactory: () => new DefaultUrlSerializer() }); }
  420. }
  421. i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "16.0.4", ngImport: i0, type: UrlSerializer, decorators: [{
  422. type: Injectable,
  423. args: [{ providedIn: 'root', useFactory: () => new DefaultUrlSerializer() }]
  424. }] });
  425. /**
  426. * @description
  427. *
  428. * A default implementation of the `UrlSerializer`.
  429. *
  430. * Example URLs:
  431. *
  432. * ```
  433. * /inbox/33(popup:compose)
  434. * /inbox/33;open=true/messages/44
  435. * ```
  436. *
  437. * DefaultUrlSerializer uses parentheses to serialize secondary segments (e.g., popup:compose), the
  438. * colon syntax to specify the outlet, and the ';parameter=value' syntax (e.g., open=true) to
  439. * specify route specific parameters.
  440. *
  441. * @publicApi
  442. */
  443. class DefaultUrlSerializer {
  444. /** Parses a url into a `UrlTree` */
  445. parse(url) {
  446. const p = new UrlParser(url);
  447. return new UrlTree(p.parseRootSegment(), p.parseQueryParams(), p.parseFragment());
  448. }
  449. /** Converts a `UrlTree` into a url */
  450. serialize(tree) {
  451. const segment = `/${serializeSegment(tree.root, true)}`;
  452. const query = serializeQueryParams(tree.queryParams);
  453. const fragment = typeof tree.fragment === `string` ? `#${encodeUriFragment(tree.fragment)}` : '';
  454. return `${segment}${query}${fragment}`;
  455. }
  456. }
  457. const DEFAULT_SERIALIZER = new DefaultUrlSerializer();
  458. function serializePaths(segment) {
  459. return segment.segments.map(p => serializePath(p)).join('/');
  460. }
  461. function serializeSegment(segment, root) {
  462. if (!segment.hasChildren()) {
  463. return serializePaths(segment);
  464. }
  465. if (root) {
  466. const primary = segment.children[PRIMARY_OUTLET] ?
  467. serializeSegment(segment.children[PRIMARY_OUTLET], false) :
  468. '';
  469. const children = [];
  470. Object.entries(segment.children).forEach(([k, v]) => {
  471. if (k !== PRIMARY_OUTLET) {
  472. children.push(`${k}:${serializeSegment(v, false)}`);
  473. }
  474. });
  475. return children.length > 0 ? `${primary}(${children.join('//')})` : primary;
  476. }
  477. else {
  478. const children = mapChildrenIntoArray(segment, (v, k) => {
  479. if (k === PRIMARY_OUTLET) {
  480. return [serializeSegment(segment.children[PRIMARY_OUTLET], false)];
  481. }
  482. return [`${k}:${serializeSegment(v, false)}`];
  483. });
  484. // use no parenthesis if the only child is a primary outlet route
  485. if (Object.keys(segment.children).length === 1 && segment.children[PRIMARY_OUTLET] != null) {
  486. return `${serializePaths(segment)}/${children[0]}`;
  487. }
  488. return `${serializePaths(segment)}/(${children.join('//')})`;
  489. }
  490. }
  491. /**
  492. * Encodes a URI string with the default encoding. This function will only ever be called from
  493. * `encodeUriQuery` or `encodeUriSegment` as it's the base set of encodings to be used. We need
  494. * a custom encoding because encodeURIComponent is too aggressive and encodes stuff that doesn't
  495. * have to be encoded per https://url.spec.whatwg.org.
  496. */
  497. function encodeUriString(s) {
  498. return encodeURIComponent(s)
  499. .replace(/%40/g, '@')
  500. .replace(/%3A/gi, ':')
  501. .replace(/%24/g, '$')
  502. .replace(/%2C/gi, ',');
  503. }
  504. /**
  505. * This function should be used to encode both keys and values in a query string key/value. In
  506. * the following URL, you need to call encodeUriQuery on "k" and "v":
  507. *
  508. * http://www.site.org/html;mk=mv?k=v#f
  509. */
  510. function encodeUriQuery(s) {
  511. return encodeUriString(s).replace(/%3B/gi, ';');
  512. }
  513. /**
  514. * This function should be used to encode a URL fragment. In the following URL, you need to call
  515. * encodeUriFragment on "f":
  516. *
  517. * http://www.site.org/html;mk=mv?k=v#f
  518. */
  519. function encodeUriFragment(s) {
  520. return encodeURI(s);
  521. }
  522. /**
  523. * This function should be run on any URI segment as well as the key and value in a key/value
  524. * pair for matrix params. In the following URL, you need to call encodeUriSegment on "html",
  525. * "mk", and "mv":
  526. *
  527. * http://www.site.org/html;mk=mv?k=v#f
  528. */
  529. function encodeUriSegment(s) {
  530. return encodeUriString(s).replace(/\(/g, '%28').replace(/\)/g, '%29').replace(/%26/gi, '&');
  531. }
  532. function decode(s) {
  533. return decodeURIComponent(s);
  534. }
  535. // Query keys/values should have the "+" replaced first, as "+" in a query string is " ".
  536. // decodeURIComponent function will not decode "+" as a space.
  537. function decodeQuery(s) {
  538. return decode(s.replace(/\+/g, '%20'));
  539. }
  540. function serializePath(path) {
  541. return `${encodeUriSegment(path.path)}${serializeMatrixParams(path.parameters)}`;
  542. }
  543. function serializeMatrixParams(params) {
  544. return Object.keys(params)
  545. .map(key => `;${encodeUriSegment(key)}=${encodeUriSegment(params[key])}`)
  546. .join('');
  547. }
  548. function serializeQueryParams(params) {
  549. const strParams = Object.keys(params)
  550. .map((name) => {
  551. const value = params[name];
  552. return Array.isArray(value) ?
  553. value.map(v => `${encodeUriQuery(name)}=${encodeUriQuery(v)}`).join('&') :
  554. `${encodeUriQuery(name)}=${encodeUriQuery(value)}`;
  555. })
  556. .filter(s => !!s);
  557. return strParams.length ? `?${strParams.join('&')}` : '';
  558. }
  559. const SEGMENT_RE = /^[^\/()?;#]+/;
  560. function matchSegments(str) {
  561. const match = str.match(SEGMENT_RE);
  562. return match ? match[0] : '';
  563. }
  564. const MATRIX_PARAM_SEGMENT_RE = /^[^\/()?;=#]+/;
  565. function matchMatrixKeySegments(str) {
  566. const match = str.match(MATRIX_PARAM_SEGMENT_RE);
  567. return match ? match[0] : '';
  568. }
  569. const QUERY_PARAM_RE = /^[^=?&#]+/;
  570. // Return the name of the query param at the start of the string or an empty string
  571. function matchQueryParams(str) {
  572. const match = str.match(QUERY_PARAM_RE);
  573. return match ? match[0] : '';
  574. }
  575. const QUERY_PARAM_VALUE_RE = /^[^&#]+/;
  576. // Return the value of the query param at the start of the string or an empty string
  577. function matchUrlQueryParamValue(str) {
  578. const match = str.match(QUERY_PARAM_VALUE_RE);
  579. return match ? match[0] : '';
  580. }
  581. class UrlParser {
  582. constructor(url) {
  583. this.url = url;
  584. this.remaining = url;
  585. }
  586. parseRootSegment() {
  587. this.consumeOptional('/');
  588. if (this.remaining === '' || this.peekStartsWith('?') || this.peekStartsWith('#')) {
  589. return new UrlSegmentGroup([], {});
  590. }
  591. // The root segment group never has segments
  592. return new UrlSegmentGroup([], this.parseChildren());
  593. }
  594. parseQueryParams() {
  595. const params = {};
  596. if (this.consumeOptional('?')) {
  597. do {
  598. this.parseQueryParam(params);
  599. } while (this.consumeOptional('&'));
  600. }
  601. return params;
  602. }
  603. parseFragment() {
  604. return this.consumeOptional('#') ? decodeURIComponent(this.remaining) : null;
  605. }
  606. parseChildren() {
  607. if (this.remaining === '') {
  608. return {};
  609. }
  610. this.consumeOptional('/');
  611. const segments = [];
  612. if (!this.peekStartsWith('(')) {
  613. segments.push(this.parseSegment());
  614. }
  615. while (this.peekStartsWith('/') && !this.peekStartsWith('//') && !this.peekStartsWith('/(')) {
  616. this.capture('/');
  617. segments.push(this.parseSegment());
  618. }
  619. let children = {};
  620. if (this.peekStartsWith('/(')) {
  621. this.capture('/');
  622. children = this.parseParens(true);
  623. }
  624. let res = {};
  625. if (this.peekStartsWith('(')) {
  626. res = this.parseParens(false);
  627. }
  628. if (segments.length > 0 || Object.keys(children).length > 0) {
  629. res[PRIMARY_OUTLET] = new UrlSegmentGroup(segments, children);
  630. }
  631. return res;
  632. }
  633. // parse a segment with its matrix parameters
  634. // ie `name;k1=v1;k2`
  635. parseSegment() {
  636. const path = matchSegments(this.remaining);
  637. if (path === '' && this.peekStartsWith(';')) {
  638. throw new ɵRuntimeError(4009 /* RuntimeErrorCode.EMPTY_PATH_WITH_PARAMS */, (typeof ngDevMode === 'undefined' || ngDevMode) &&
  639. `Empty path url segment cannot have parameters: '${this.remaining}'.`);
  640. }
  641. this.capture(path);
  642. return new UrlSegment(decode(path), this.parseMatrixParams());
  643. }
  644. parseMatrixParams() {
  645. const params = {};
  646. while (this.consumeOptional(';')) {
  647. this.parseParam(params);
  648. }
  649. return params;
  650. }
  651. parseParam(params) {
  652. const key = matchMatrixKeySegments(this.remaining);
  653. if (!key) {
  654. return;
  655. }
  656. this.capture(key);
  657. let value = '';
  658. if (this.consumeOptional('=')) {
  659. const valueMatch = matchSegments(this.remaining);
  660. if (valueMatch) {
  661. value = valueMatch;
  662. this.capture(value);
  663. }
  664. }
  665. params[decode(key)] = decode(value);
  666. }
  667. // Parse a single query parameter `name[=value]`
  668. parseQueryParam(params) {
  669. const key = matchQueryParams(this.remaining);
  670. if (!key) {
  671. return;
  672. }
  673. this.capture(key);
  674. let value = '';
  675. if (this.consumeOptional('=')) {
  676. const valueMatch = matchUrlQueryParamValue(this.remaining);
  677. if (valueMatch) {
  678. value = valueMatch;
  679. this.capture(value);
  680. }
  681. }
  682. const decodedKey = decodeQuery(key);
  683. const decodedVal = decodeQuery(value);
  684. if (params.hasOwnProperty(decodedKey)) {
  685. // Append to existing values
  686. let currentVal = params[decodedKey];
  687. if (!Array.isArray(currentVal)) {
  688. currentVal = [currentVal];
  689. params[decodedKey] = currentVal;
  690. }
  691. currentVal.push(decodedVal);
  692. }
  693. else {
  694. // Create a new value
  695. params[decodedKey] = decodedVal;
  696. }
  697. }
  698. // parse `(a/b//outlet_name:c/d)`
  699. parseParens(allowPrimary) {
  700. const segments = {};
  701. this.capture('(');
  702. while (!this.consumeOptional(')') && this.remaining.length > 0) {
  703. const path = matchSegments(this.remaining);
  704. const next = this.remaining[path.length];
  705. // if is is not one of these characters, then the segment was unescaped
  706. // or the group was not closed
  707. if (next !== '/' && next !== ')' && next !== ';') {
  708. throw new ɵRuntimeError(4010 /* RuntimeErrorCode.UNPARSABLE_URL */, (typeof ngDevMode === 'undefined' || ngDevMode) && `Cannot parse url '${this.url}'`);
  709. }
  710. let outletName = undefined;
  711. if (path.indexOf(':') > -1) {
  712. outletName = path.slice(0, path.indexOf(':'));
  713. this.capture(outletName);
  714. this.capture(':');
  715. }
  716. else if (allowPrimary) {
  717. outletName = PRIMARY_OUTLET;
  718. }
  719. const children = this.parseChildren();
  720. segments[outletName] = Object.keys(children).length === 1 ? children[PRIMARY_OUTLET] :
  721. new UrlSegmentGroup([], children);
  722. this.consumeOptional('//');
  723. }
  724. return segments;
  725. }
  726. peekStartsWith(str) {
  727. return this.remaining.startsWith(str);
  728. }
  729. // Consumes the prefix when it is present and returns whether it has been consumed
  730. consumeOptional(str) {
  731. if (this.peekStartsWith(str)) {
  732. this.remaining = this.remaining.substring(str.length);
  733. return true;
  734. }
  735. return false;
  736. }
  737. capture(str) {
  738. if (!this.consumeOptional(str)) {
  739. throw new ɵRuntimeError(4011 /* RuntimeErrorCode.UNEXPECTED_VALUE_IN_URL */, (typeof ngDevMode === 'undefined' || ngDevMode) && `Expected "${str}".`);
  740. }
  741. }
  742. }
  743. function createRoot(rootCandidate) {
  744. return rootCandidate.segments.length > 0 ?
  745. new UrlSegmentGroup([], { [PRIMARY_OUTLET]: rootCandidate }) :
  746. rootCandidate;
  747. }
  748. /**
  749. * Recursively
  750. * - merges primary segment children into their parents
  751. * - drops empty children (those which have no segments and no children themselves). This latter
  752. * prevents serializing a group into something like `/a(aux:)`, where `aux` is an empty child
  753. * segment.
  754. * - merges named outlets without a primary segment sibling into the children. This prevents
  755. * serializing a URL like `//(a:a)(b:b) instead of `/(a:a//b:b)` when the aux b route lives on the
  756. * root but the `a` route lives under an empty path primary route.
  757. */
  758. function squashSegmentGroup(segmentGroup) {
  759. const newChildren = {};
  760. for (const childOutlet of Object.keys(segmentGroup.children)) {
  761. const child = segmentGroup.children[childOutlet];
  762. const childCandidate = squashSegmentGroup(child);
  763. // moves named children in an empty path primary child into this group
  764. if (childOutlet === PRIMARY_OUTLET && childCandidate.segments.length === 0 &&
  765. childCandidate.hasChildren()) {
  766. for (const [grandChildOutlet, grandChild] of Object.entries(childCandidate.children)) {
  767. newChildren[grandChildOutlet] = grandChild;
  768. }
  769. } // don't add empty children
  770. else if (childCandidate.segments.length > 0 || childCandidate.hasChildren()) {
  771. newChildren[childOutlet] = childCandidate;
  772. }
  773. }
  774. const s = new UrlSegmentGroup(segmentGroup.segments, newChildren);
  775. return mergeTrivialChildren(s);
  776. }
  777. /**
  778. * When possible, merges the primary outlet child into the parent `UrlSegmentGroup`.
  779. *
  780. * When a segment group has only one child which is a primary outlet, merges that child into the
  781. * parent. That is, the child segment group's segments are merged into the `s` and the child's
  782. * children become the children of `s`. Think of this like a 'squash', merging the child segment
  783. * group into the parent.
  784. */
  785. function mergeTrivialChildren(s) {
  786. if (s.numberOfChildren === 1 && s.children[PRIMARY_OUTLET]) {
  787. const c = s.children[PRIMARY_OUTLET];
  788. return new UrlSegmentGroup(s.segments.concat(c.segments), c.children);
  789. }
  790. return s;
  791. }
  792. function isUrlTree(v) {
  793. return v instanceof UrlTree;
  794. }
  795. /**
  796. * Creates a `UrlTree` relative to an `ActivatedRouteSnapshot`.
  797. *
  798. * @publicApi
  799. *
  800. *
  801. * @param relativeTo The `ActivatedRouteSnapshot` to apply the commands to
  802. * @param commands An array of URL fragments with which to construct the new URL tree.
  803. * If the path is static, can be the literal URL string. For a dynamic path, pass an array of path
  804. * segments, followed by the parameters for each segment.
  805. * The fragments are applied to the one provided in the `relativeTo` parameter.
  806. * @param queryParams The query parameters for the `UrlTree`. `null` if the `UrlTree` does not have
  807. * any query parameters.
  808. * @param fragment The fragment for the `UrlTree`. `null` if the `UrlTree` does not have a fragment.
  809. *
  810. * @usageNotes
  811. *
  812. * ```
  813. * // create /team/33/user/11
  814. * createUrlTreeFromSnapshot(snapshot, ['/team', 33, 'user', 11]);
  815. *
  816. * // create /team/33;expand=true/user/11
  817. * createUrlTreeFromSnapshot(snapshot, ['/team', 33, {expand: true}, 'user', 11]);
  818. *
  819. * // you can collapse static segments like this (this works only with the first passed-in value):
  820. * createUrlTreeFromSnapshot(snapshot, ['/team/33/user', userId]);
  821. *
  822. * // If the first segment can contain slashes, and you do not want the router to split it,
  823. * // you can do the following:
  824. * createUrlTreeFromSnapshot(snapshot, [{segmentPath: '/one/two'}]);
  825. *
  826. * // create /team/33/(user/11//right:chat)
  827. * createUrlTreeFromSnapshot(snapshot, ['/team', 33, {outlets: {primary: 'user/11', right:
  828. * 'chat'}}], null, null);
  829. *
  830. * // remove the right secondary node
  831. * createUrlTreeFromSnapshot(snapshot, ['/team', 33, {outlets: {primary: 'user/11', right: null}}]);
  832. *
  833. * // For the examples below, assume the current URL is for the `/team/33/user/11` and the
  834. * `ActivatedRouteSnapshot` points to `user/11`:
  835. *
  836. * // navigate to /team/33/user/11/details
  837. * createUrlTreeFromSnapshot(snapshot, ['details']);
  838. *
  839. * // navigate to /team/33/user/22
  840. * createUrlTreeFromSnapshot(snapshot, ['../22']);
  841. *
  842. * // navigate to /team/44/user/22
  843. * createUrlTreeFromSnapshot(snapshot, ['../../team/44/user/22']);
  844. * ```
  845. */
  846. function createUrlTreeFromSnapshot(relativeTo, commands, queryParams = null, fragment = null) {
  847. const relativeToUrlSegmentGroup = createSegmentGroupFromRoute(relativeTo);
  848. return createUrlTreeFromSegmentGroup(relativeToUrlSegmentGroup, commands, queryParams, fragment);
  849. }
  850. function createSegmentGroupFromRoute(route) {
  851. let targetGroup;
  852. function createSegmentGroupFromRouteRecursive(currentRoute) {
  853. const childOutlets = {};
  854. for (const childSnapshot of currentRoute.children) {
  855. const root = createSegmentGroupFromRouteRecursive(childSnapshot);
  856. childOutlets[childSnapshot.outlet] = root;
  857. }
  858. const segmentGroup = new UrlSegmentGroup(currentRoute.url, childOutlets);
  859. if (currentRoute === route) {
  860. targetGroup = segmentGroup;
  861. }
  862. return segmentGroup;
  863. }
  864. const rootCandidate = createSegmentGroupFromRouteRecursive(route.root);
  865. const rootSegmentGroup = createRoot(rootCandidate);
  866. return targetGroup ?? rootSegmentGroup;
  867. }
  868. function createUrlTreeFromSegmentGroup(relativeTo, commands, queryParams, fragment) {
  869. let root = relativeTo;
  870. while (root.parent) {
  871. root = root.parent;
  872. }
  873. // There are no commands so the `UrlTree` goes to the same path as the one created from the
  874. // `UrlSegmentGroup`. All we need to do is update the `queryParams` and `fragment` without
  875. // applying any other logic.
  876. if (commands.length === 0) {
  877. return tree(root, root, root, queryParams, fragment);
  878. }
  879. const nav = computeNavigation(commands);
  880. if (nav.toRoot()) {
  881. return tree(root, root, new UrlSegmentGroup([], {}), queryParams, fragment);
  882. }
  883. const position = findStartingPositionForTargetGroup(nav, root, relativeTo);
  884. const newSegmentGroup = position.processChildren ?
  885. updateSegmentGroupChildren(position.segmentGroup, position.index, nav.commands) :
  886. updateSegmentGroup(position.segmentGroup, position.index, nav.commands);
  887. return tree(root, position.segmentGroup, newSegmentGroup, queryParams, fragment);
  888. }
  889. function isMatrixParams(command) {
  890. return typeof command === 'object' && command != null && !command.outlets && !command.segmentPath;
  891. }
  892. /**
  893. * Determines if a given command has an `outlets` map. When we encounter a command
  894. * with an outlets k/v map, we need to apply each outlet individually to the existing segment.
  895. */
  896. function isCommandWithOutlets(command) {
  897. return typeof command === 'object' && command != null && command.outlets;
  898. }
  899. function tree(oldRoot, oldSegmentGroup, newSegmentGroup, queryParams, fragment) {
  900. let qp = {};
  901. if (queryParams) {
  902. Object.entries(queryParams).forEach(([name, value]) => {
  903. qp[name] = Array.isArray(value) ? value.map((v) => `${v}`) : `${value}`;
  904. });
  905. }
  906. let rootCandidate;
  907. if (oldRoot === oldSegmentGroup) {
  908. rootCandidate = newSegmentGroup;
  909. }
  910. else {
  911. rootCandidate = replaceSegment(oldRoot, oldSegmentGroup, newSegmentGroup);
  912. }
  913. const newRoot = createRoot(squashSegmentGroup(rootCandidate));
  914. return new UrlTree(newRoot, qp, fragment);
  915. }
  916. /**
  917. * Replaces the `oldSegment` which is located in some child of the `current` with the `newSegment`.
  918. * This also has the effect of creating new `UrlSegmentGroup` copies to update references. This
  919. * shouldn't be necessary but the fallback logic for an invalid ActivatedRoute in the creation uses
  920. * the Router's current url tree. If we don't create new segment groups, we end up modifying that
  921. * value.
  922. */
  923. function replaceSegment(current, oldSegment, newSegment) {
  924. const children = {};
  925. Object.entries(current.children).forEach(([outletName, c]) => {
  926. if (c === oldSegment) {
  927. children[outletName] = newSegment;
  928. }
  929. else {
  930. children[outletName] = replaceSegment(c, oldSegment, newSegment);
  931. }
  932. });
  933. return new UrlSegmentGroup(current.segments, children);
  934. }
  935. class Navigation {
  936. constructor(isAbsolute, numberOfDoubleDots, commands) {
  937. this.isAbsolute = isAbsolute;
  938. this.numberOfDoubleDots = numberOfDoubleDots;
  939. this.commands = commands;
  940. if (isAbsolute && commands.length > 0 && isMatrixParams(commands[0])) {
  941. throw new ɵRuntimeError(4003 /* RuntimeErrorCode.ROOT_SEGMENT_MATRIX_PARAMS */, (typeof ngDevMode === 'undefined' || ngDevMode) &&
  942. 'Root segment cannot have matrix parameters');
  943. }
  944. const cmdWithOutlet = commands.find(isCommandWithOutlets);
  945. if (cmdWithOutlet && cmdWithOutlet !== last(commands)) {
  946. throw new ɵRuntimeError(4004 /* RuntimeErrorCode.MISPLACED_OUTLETS_COMMAND */, (typeof ngDevMode === 'undefined' || ngDevMode) &&
  947. '{outlets:{}} has to be the last command');
  948. }
  949. }
  950. toRoot() {
  951. return this.isAbsolute && this.commands.length === 1 && this.commands[0] == '/';
  952. }
  953. }
  954. /** Transforms commands to a normalized `Navigation` */
  955. function computeNavigation(commands) {
  956. if ((typeof commands[0] === 'string') && commands.length === 1 && commands[0] === '/') {
  957. return new Navigation(true, 0, commands);
  958. }
  959. let numberOfDoubleDots = 0;
  960. let isAbsolute = false;
  961. const res = commands.reduce((res, cmd, cmdIdx) => {
  962. if (typeof cmd === 'object' && cmd != null) {
  963. if (cmd.outlets) {
  964. const outlets = {};
  965. Object.entries(cmd.outlets).forEach(([name, commands]) => {
  966. outlets[name] = typeof commands === 'string' ? commands.split('/') : commands;
  967. });
  968. return [...res, { outlets }];
  969. }
  970. if (cmd.segmentPath) {
  971. return [...res, cmd.segmentPath];
  972. }
  973. }
  974. if (!(typeof cmd === 'string')) {
  975. return [...res, cmd];
  976. }
  977. if (cmdIdx === 0) {
  978. cmd.split('/').forEach((urlPart, partIndex) => {
  979. if (partIndex == 0 && urlPart === '.') {
  980. // skip './a'
  981. }
  982. else if (partIndex == 0 && urlPart === '') { // '/a'
  983. isAbsolute = true;
  984. }
  985. else if (urlPart === '..') { // '../a'
  986. numberOfDoubleDots++;
  987. }
  988. else if (urlPart != '') {
  989. res.push(urlPart);
  990. }
  991. });
  992. return res;
  993. }
  994. return [...res, cmd];
  995. }, []);
  996. return new Navigation(isAbsolute, numberOfDoubleDots, res);
  997. }
  998. class Position {
  999. constructor(segmentGroup, processChildren, index) {
  1000. this.segmentGroup = segmentGroup;
  1001. this.processChildren = processChildren;
  1002. this.index = index;
  1003. }
  1004. }
  1005. function findStartingPositionForTargetGroup(nav, root, target) {
  1006. if (nav.isAbsolute) {
  1007. return new Position(root, true, 0);
  1008. }
  1009. if (!target) {
  1010. // `NaN` is used only to maintain backwards compatibility with incorrectly mocked
  1011. // `ActivatedRouteSnapshot` in tests. In prior versions of this code, the position here was
  1012. // determined based on an internal property that was rarely mocked, resulting in `NaN`. In
  1013. // reality, this code path should _never_ be touched since `target` is not allowed to be falsey.
  1014. return new Position(root, false, NaN);
  1015. }
  1016. if (target.parent === null) {
  1017. return new Position(target, true, 0);
  1018. }
  1019. const modifier = isMatrixParams(nav.commands[0]) ? 0 : 1;
  1020. const index = target.segments.length - 1 + modifier;
  1021. return createPositionApplyingDoubleDots(target, index, nav.numberOfDoubleDots);
  1022. }
  1023. function createPositionApplyingDoubleDots(group, index, numberOfDoubleDots) {
  1024. let g = group;
  1025. let ci = index;
  1026. let dd = numberOfDoubleDots;
  1027. while (dd > ci) {
  1028. dd -= ci;
  1029. g = g.parent;
  1030. if (!g) {
  1031. throw new ɵRuntimeError(4005 /* RuntimeErrorCode.INVALID_DOUBLE_DOTS */, (typeof ngDevMode === 'undefined' || ngDevMode) && 'Invalid number of \'../\'');
  1032. }
  1033. ci = g.segments.length;
  1034. }
  1035. return new Position(g, false, ci - dd);
  1036. }
  1037. function getOutlets(commands) {
  1038. if (isCommandWithOutlets(commands[0])) {
  1039. return commands[0].outlets;
  1040. }
  1041. return { [PRIMARY_OUTLET]: commands };
  1042. }
  1043. function updateSegmentGroup(segmentGroup, startIndex, commands) {
  1044. if (!segmentGroup) {
  1045. segmentGroup = new UrlSegmentGroup([], {});
  1046. }
  1047. if (segmentGroup.segments.length === 0 && segmentGroup.hasChildren()) {
  1048. return updateSegmentGroupChildren(segmentGroup, startIndex, commands);
  1049. }
  1050. const m = prefixedWith(segmentGroup, startIndex, commands);
  1051. const slicedCommands = commands.slice(m.commandIndex);
  1052. if (m.match && m.pathIndex < segmentGroup.segments.length) {
  1053. const g = new UrlSegmentGroup(segmentGroup.segments.slice(0, m.pathIndex), {});
  1054. g.children[PRIMARY_OUTLET] =
  1055. new UrlSegmentGroup(segmentGroup.segments.slice(m.pathIndex), segmentGroup.children);
  1056. return updateSegmentGroupChildren(g, 0, slicedCommands);
  1057. }
  1058. else if (m.match && slicedCommands.length === 0) {
  1059. return new UrlSegmentGroup(segmentGroup.segments, {});
  1060. }
  1061. else if (m.match && !segmentGroup.hasChildren()) {
  1062. return createNewSegmentGroup(segmentGroup, startIndex, commands);
  1063. }
  1064. else if (m.match) {
  1065. return updateSegmentGroupChildren(segmentGroup, 0, slicedCommands);
  1066. }
  1067. else {
  1068. return createNewSegmentGroup(segmentGroup, startIndex, commands);
  1069. }
  1070. }
  1071. function updateSegmentGroupChildren(segmentGroup, startIndex, commands) {
  1072. if (commands.length === 0) {
  1073. return new UrlSegmentGroup(segmentGroup.segments, {});
  1074. }
  1075. else {
  1076. const outlets = getOutlets(commands);
  1077. const children = {};
  1078. // If the set of commands does not apply anything to the primary outlet and the child segment is
  1079. // an empty path primary segment on its own, we want to apply the commands to the empty child
  1080. // path rather than here. The outcome is that the empty primary child is effectively removed
  1081. // from the final output UrlTree. Imagine the following config:
  1082. //
  1083. // {path: '', children: [{path: '**', outlet: 'popup'}]}.
  1084. //
  1085. // Navigation to /(popup:a) will activate the child outlet correctly Given a follow-up
  1086. // navigation with commands
  1087. // ['/', {outlets: {'popup': 'b'}}], we _would not_ want to apply the outlet commands to the
  1088. // root segment because that would result in
  1089. // //(popup:a)(popup:b) since the outlet command got applied one level above where it appears in
  1090. // the `ActivatedRoute` rather than updating the existing one.
  1091. //
  1092. // Because empty paths do not appear in the URL segments and the fact that the segments used in
  1093. // the output `UrlTree` are squashed to eliminate these empty paths where possible
  1094. // https://github.com/angular/angular/blob/13f10de40e25c6900ca55bd83b36bd533dacfa9e/packages/router/src/url_tree.ts#L755
  1095. // it can be hard to determine what is the right thing to do when applying commands to a
  1096. // `UrlSegmentGroup` that is created from an "unsquashed"/expanded `ActivatedRoute` tree.
  1097. // This code effectively "squashes" empty path primary routes when they have no siblings on
  1098. // the same level of the tree.
  1099. if (!outlets[PRIMARY_OUTLET] && segmentGroup.children[PRIMARY_OUTLET] &&
  1100. segmentGroup.numberOfChildren === 1 &&
  1101. segmentGroup.children[PRIMARY_OUTLET].segments.length === 0) {
  1102. const childrenOfEmptyChild = updateSegmentGroupChildren(segmentGroup.children[PRIMARY_OUTLET], startIndex, commands);
  1103. return new UrlSegmentGroup(segmentGroup.segments, childrenOfEmptyChild.children);
  1104. }
  1105. Object.entries(outlets).forEach(([outlet, commands]) => {
  1106. if (typeof commands === 'string') {
  1107. commands = [commands];
  1108. }
  1109. if (commands !== null) {
  1110. children[outlet] = updateSegmentGroup(segmentGroup.children[outlet], startIndex, commands);
  1111. }
  1112. });
  1113. Object.entries(segmentGroup.children).forEach(([childOutlet, child]) => {
  1114. if (outlets[childOutlet] === undefined) {
  1115. children[childOutlet] = child;
  1116. }
  1117. });
  1118. return new UrlSegmentGroup(segmentGroup.segments, children);
  1119. }
  1120. }
  1121. function prefixedWith(segmentGroup, startIndex, commands) {
  1122. let currentCommandIndex = 0;
  1123. let currentPathIndex = startIndex;
  1124. const noMatch = { match: false, pathIndex: 0, commandIndex: 0 };
  1125. while (currentPathIndex < segmentGroup.segments.length) {
  1126. if (currentCommandIndex >= commands.length)
  1127. return noMatch;
  1128. const path = segmentGroup.segments[currentPathIndex];
  1129. const command = commands[currentCommandIndex];
  1130. // Do not try to consume command as part of the prefixing if it has outlets because it can
  1131. // contain outlets other than the one being processed. Consuming the outlets command would
  1132. // result in other outlets being ignored.
  1133. if (isCommandWithOutlets(command)) {
  1134. break;
  1135. }
  1136. const curr = `${command}`;
  1137. const next = currentCommandIndex < commands.length - 1 ? commands[currentCommandIndex + 1] : null;
  1138. if (currentPathIndex > 0 && curr === undefined)
  1139. break;
  1140. if (curr && next && (typeof next === 'object') && next.outlets === undefined) {
  1141. if (!compare(curr, next, path))
  1142. return noMatch;
  1143. currentCommandIndex += 2;
  1144. }
  1145. else {
  1146. if (!compare(curr, {}, path))
  1147. return noMatch;
  1148. currentCommandIndex++;
  1149. }
  1150. currentPathIndex++;
  1151. }
  1152. return { match: true, pathIndex: currentPathIndex, commandIndex: currentCommandIndex };
  1153. }
  1154. function createNewSegmentGroup(segmentGroup, startIndex, commands) {
  1155. const paths = segmentGroup.segments.slice(0, startIndex);
  1156. let i = 0;
  1157. while (i < commands.length) {
  1158. const command = commands[i];
  1159. if (isCommandWithOutlets(command)) {
  1160. const children = createNewSegmentChildren(command.outlets);
  1161. return new UrlSegmentGroup(paths, children);
  1162. }
  1163. // if we start with an object literal, we need to reuse the path part from the segment
  1164. if (i === 0 && isMatrixParams(commands[0])) {
  1165. const p = segmentGroup.segments[startIndex];
  1166. paths.push(new UrlSegment(p.path, stringify(commands[0])));
  1167. i++;
  1168. continue;
  1169. }
  1170. const curr = isCommandWithOutlets(command) ? command.outlets[PRIMARY_OUTLET] : `${command}`;
  1171. const next = (i < commands.length - 1) ? commands[i + 1] : null;
  1172. if (curr && next && isMatrixParams(next)) {
  1173. paths.push(new UrlSegment(curr, stringify(next)));
  1174. i += 2;
  1175. }
  1176. else {
  1177. paths.push(new UrlSegment(curr, {}));
  1178. i++;
  1179. }
  1180. }
  1181. return new UrlSegmentGroup(paths, {});
  1182. }
  1183. function createNewSegmentChildren(outlets) {
  1184. const children = {};
  1185. Object.entries(outlets).forEach(([outlet, commands]) => {
  1186. if (typeof commands === 'string') {
  1187. commands = [commands];
  1188. }
  1189. if (commands !== null) {
  1190. children[outlet] = createNewSegmentGroup(new UrlSegmentGroup([], {}), 0, commands);
  1191. }
  1192. });
  1193. return children;
  1194. }
  1195. function stringify(params) {
  1196. const res = {};
  1197. Object.entries(params).forEach(([k, v]) => res[k] = `${v}`);
  1198. return res;
  1199. }
  1200. function compare(path, params, segment) {
  1201. return path == segment.path && shallowEqual(params, segment.parameters);
  1202. }
  1203. const IMPERATIVE_NAVIGATION = 'imperative';
  1204. /**
  1205. * Base for events the router goes through, as opposed to events tied to a specific
  1206. * route. Fired one time for any given navigation.
  1207. *
  1208. * The following code shows how a class subscribes to router events.
  1209. *
  1210. * ```ts
  1211. * import {Event, RouterEvent, Router} from '@angular/router';
  1212. *
  1213. * class MyService {
  1214. * constructor(public router: Router) {
  1215. * router.events.pipe(
  1216. * filter((e: Event): e is RouterEvent => e instanceof RouterEvent)
  1217. * ).subscribe((e: RouterEvent) => {
  1218. * // Do something
  1219. * });
  1220. * }
  1221. * }
  1222. * ```
  1223. *
  1224. * @see `Event`
  1225. * @see [Router events summary](guide/router-reference#router-events)
  1226. * @publicApi
  1227. */
  1228. class RouterEvent {
  1229. constructor(
  1230. /** A unique ID that the router assigns to every router navigation. */
  1231. id,
  1232. /** The URL that is the destination for this navigation. */
  1233. url) {
  1234. this.id = id;
  1235. this.url = url;
  1236. }
  1237. }
  1238. /**
  1239. * An event triggered when a navigation starts.
  1240. *
  1241. * @publicApi
  1242. */
  1243. class NavigationStart extends RouterEvent {
  1244. constructor(
  1245. /** @docsNotRequired */
  1246. id,
  1247. /** @docsNotRequired */
  1248. url,
  1249. /** @docsNotRequired */
  1250. navigationTrigger = 'imperative',
  1251. /** @docsNotRequired */
  1252. restoredState = null) {
  1253. super(id, url);
  1254. this.type = 0 /* EventType.NavigationStart */;
  1255. this.navigationTrigger = navigationTrigger;
  1256. this.restoredState = restoredState;
  1257. }
  1258. /** @docsNotRequired */
  1259. toString() {
  1260. return `NavigationStart(id: ${this.id}, url: '${this.url}')`;
  1261. }
  1262. }
  1263. /**
  1264. * An event triggered when a navigation ends successfully.
  1265. *
  1266. * @see `NavigationStart`
  1267. * @see `NavigationCancel`
  1268. * @see `NavigationError`
  1269. *
  1270. * @publicApi
  1271. */
  1272. class NavigationEnd extends RouterEvent {
  1273. constructor(
  1274. /** @docsNotRequired */
  1275. id,
  1276. /** @docsNotRequired */
  1277. url,
  1278. /** @docsNotRequired */
  1279. urlAfterRedirects) {
  1280. super(id, url);
  1281. this.urlAfterRedirects = urlAfterRedirects;
  1282. this.type = 1 /* EventType.NavigationEnd */;
  1283. }
  1284. /** @docsNotRequired */
  1285. toString() {
  1286. return `NavigationEnd(id: ${this.id}, url: '${this.url}', urlAfterRedirects: '${this.urlAfterRedirects}')`;
  1287. }
  1288. }
  1289. /**
  1290. * An event triggered when a navigation is canceled, directly or indirectly.
  1291. * This can happen for several reasons including when a route guard
  1292. * returns `false` or initiates a redirect by returning a `UrlTree`.
  1293. *
  1294. * @see `NavigationStart`
  1295. * @see `NavigationEnd`
  1296. * @see `NavigationError`
  1297. *
  1298. * @publicApi
  1299. */
  1300. class NavigationCancel extends RouterEvent {
  1301. constructor(
  1302. /** @docsNotRequired */
  1303. id,
  1304. /** @docsNotRequired */
  1305. url,
  1306. /**
  1307. * A description of why the navigation was cancelled. For debug purposes only. Use `code`
  1308. * instead for a stable cancellation reason that can be used in production.
  1309. */
  1310. reason,
  1311. /**
  1312. * A code to indicate why the navigation was canceled. This cancellation code is stable for
  1313. * the reason and can be relied on whereas the `reason` string could change and should not be
  1314. * used in production.
  1315. */
  1316. code) {
  1317. super(id, url);
  1318. this.reason = reason;
  1319. this.code = code;
  1320. this.type = 2 /* EventType.NavigationCancel */;
  1321. }
  1322. /** @docsNotRequired */
  1323. toString() {
  1324. return `NavigationCancel(id: ${this.id}, url: '${this.url}')`;
  1325. }
  1326. }
  1327. /**
  1328. * An event triggered when a navigation is skipped.
  1329. * This can happen for a couple reasons including onSameUrlHandling
  1330. * is set to `ignore` and the navigation URL is not different than the
  1331. * current state.
  1332. *
  1333. * @publicApi
  1334. */
  1335. class NavigationSkipped extends RouterEvent {
  1336. constructor(
  1337. /** @docsNotRequired */
  1338. id,
  1339. /** @docsNotRequired */
  1340. url,
  1341. /**
  1342. * A description of why the navigation was skipped. For debug purposes only. Use `code`
  1343. * instead for a stable skipped reason that can be used in production.
  1344. */
  1345. reason,
  1346. /**
  1347. * A code to indicate why the navigation was skipped. This code is stable for
  1348. * the reason and can be relied on whereas the `reason` string could change and should not be
  1349. * used in production.
  1350. */
  1351. code) {
  1352. super(id, url);
  1353. this.reason = reason;
  1354. this.code = code;
  1355. this.type = 16 /* EventType.NavigationSkipped */;
  1356. }
  1357. }
  1358. /**
  1359. * An event triggered when a navigation fails due to an unexpected error.
  1360. *
  1361. * @see `NavigationStart`
  1362. * @see `NavigationEnd`
  1363. * @see `NavigationCancel`
  1364. *
  1365. * @publicApi
  1366. */
  1367. class NavigationError extends RouterEvent {
  1368. constructor(
  1369. /** @docsNotRequired */
  1370. id,
  1371. /** @docsNotRequired */
  1372. url,
  1373. /** @docsNotRequired */
  1374. error,
  1375. /**
  1376. * The target of the navigation when the error occurred.
  1377. *
  1378. * Note that this can be `undefined` because an error could have occurred before the
  1379. * `RouterStateSnapshot` was created for the navigation.
  1380. */
  1381. target) {
  1382. super(id, url);
  1383. this.error = error;
  1384. this.target = target;
  1385. this.type = 3 /* EventType.NavigationError */;
  1386. }
  1387. /** @docsNotRequired */
  1388. toString() {
  1389. return `NavigationError(id: ${this.id}, url: '${this.url}', error: ${this.error})`;
  1390. }
  1391. }
  1392. /**
  1393. * An event triggered when routes are recognized.
  1394. *
  1395. * @publicApi
  1396. */
  1397. class RoutesRecognized extends RouterEvent {
  1398. constructor(
  1399. /** @docsNotRequired */
  1400. id,
  1401. /** @docsNotRequired */
  1402. url,
  1403. /** @docsNotRequired */
  1404. urlAfterRedirects,
  1405. /** @docsNotRequired */
  1406. state) {
  1407. super(id, url);
  1408. this.urlAfterRedirects = urlAfterRedirects;
  1409. this.state = state;
  1410. this.type = 4 /* EventType.RoutesRecognized */;
  1411. }
  1412. /** @docsNotRequired */
  1413. toString() {
  1414. return `RoutesRecognized(id: ${this.id}, url: '${this.url}', urlAfterRedirects: '${this.urlAfterRedirects}', state: ${this.state})`;
  1415. }
  1416. }
  1417. /**
  1418. * An event triggered at the start of the Guard phase of routing.
  1419. *
  1420. * @see `GuardsCheckEnd`
  1421. *
  1422. * @publicApi
  1423. */
  1424. class GuardsCheckStart extends RouterEvent {
  1425. constructor(
  1426. /** @docsNotRequired */
  1427. id,
  1428. /** @docsNotRequired */
  1429. url,
  1430. /** @docsNotRequired */
  1431. urlAfterRedirects,
  1432. /** @docsNotRequired */
  1433. state) {
  1434. super(id, url);
  1435. this.urlAfterRedirects = urlAfterRedirects;
  1436. this.state = state;
  1437. this.type = 7 /* EventType.GuardsCheckStart */;
  1438. }
  1439. toString() {
  1440. return `GuardsCheckStart(id: ${this.id}, url: '${this.url}', urlAfterRedirects: '${this.urlAfterRedirects}', state: ${this.state})`;
  1441. }
  1442. }
  1443. /**
  1444. * An event triggered at the end of the Guard phase of routing.
  1445. *
  1446. * @see `GuardsCheckStart`
  1447. *
  1448. * @publicApi
  1449. */
  1450. class GuardsCheckEnd extends RouterEvent {
  1451. constructor(
  1452. /** @docsNotRequired */
  1453. id,
  1454. /** @docsNotRequired */
  1455. url,
  1456. /** @docsNotRequired */
  1457. urlAfterRedirects,
  1458. /** @docsNotRequired */
  1459. state,
  1460. /** @docsNotRequired */
  1461. shouldActivate) {
  1462. super(id, url);
  1463. this.urlAfterRedirects = urlAfterRedirects;
  1464. this.state = state;
  1465. this.shouldActivate = shouldActivate;
  1466. this.type = 8 /* EventType.GuardsCheckEnd */;
  1467. }
  1468. toString() {
  1469. return `GuardsCheckEnd(id: ${this.id}, url: '${this.url}', urlAfterRedirects: '${this.urlAfterRedirects}', state: ${this.state}, shouldActivate: ${this.shouldActivate})`;
  1470. }
  1471. }
  1472. /**
  1473. * An event triggered at the start of the Resolve phase of routing.
  1474. *
  1475. * Runs in the "resolve" phase whether or not there is anything to resolve.
  1476. * In future, may change to only run when there are things to be resolved.
  1477. *
  1478. * @see `ResolveEnd`
  1479. *
  1480. * @publicApi
  1481. */
  1482. class ResolveStart extends RouterEvent {
  1483. constructor(
  1484. /** @docsNotRequired */
  1485. id,
  1486. /** @docsNotRequired */
  1487. url,
  1488. /** @docsNotRequired */
  1489. urlAfterRedirects,
  1490. /** @docsNotRequired */
  1491. state) {
  1492. super(id, url);
  1493. this.urlAfterRedirects = urlAfterRedirects;
  1494. this.state = state;
  1495. this.type = 5 /* EventType.ResolveStart */;
  1496. }
  1497. toString() {
  1498. return `ResolveStart(id: ${this.id}, url: '${this.url}', urlAfterRedirects: '${this.urlAfterRedirects}', state: ${this.state})`;
  1499. }
  1500. }
  1501. /**
  1502. * An event triggered at the end of the Resolve phase of routing.
  1503. * @see `ResolveStart`.
  1504. *
  1505. * @publicApi
  1506. */
  1507. class ResolveEnd extends RouterEvent {
  1508. constructor(
  1509. /** @docsNotRequired */
  1510. id,
  1511. /** @docsNotRequired */
  1512. url,
  1513. /** @docsNotRequired */
  1514. urlAfterRedirects,
  1515. /** @docsNotRequired */
  1516. state) {
  1517. super(id, url);
  1518. this.urlAfterRedirects = urlAfterRedirects;
  1519. this.state = state;
  1520. this.type = 6 /* EventType.ResolveEnd */;
  1521. }
  1522. toString() {
  1523. return `ResolveEnd(id: ${this.id}, url: '${this.url}', urlAfterRedirects: '${this.urlAfterRedirects}', state: ${this.state})`;
  1524. }
  1525. }
  1526. /**
  1527. * An event triggered before lazy loading a route configuration.
  1528. *
  1529. * @see `RouteConfigLoadEnd`
  1530. *
  1531. * @publicApi
  1532. */
  1533. class RouteConfigLoadStart {
  1534. constructor(
  1535. /** @docsNotRequired */
  1536. route) {
  1537. this.route = route;
  1538. this.type = 9 /* EventType.RouteConfigLoadStart */;
  1539. }
  1540. toString() {
  1541. return `RouteConfigLoadStart(path: ${this.route.path})`;
  1542. }
  1543. }
  1544. /**
  1545. * An event triggered when a route has been lazy loaded.
  1546. *
  1547. * @see `RouteConfigLoadStart`
  1548. *
  1549. * @publicApi
  1550. */
  1551. class RouteConfigLoadEnd {
  1552. constructor(
  1553. /** @docsNotRequired */
  1554. route) {
  1555. this.route = route;
  1556. this.type = 10 /* EventType.RouteConfigLoadEnd */;
  1557. }
  1558. toString() {
  1559. return `RouteConfigLoadEnd(path: ${this.route.path})`;
  1560. }
  1561. }
  1562. /**
  1563. * An event triggered at the start of the child-activation
  1564. * part of the Resolve phase of routing.
  1565. * @see `ChildActivationEnd`
  1566. * @see `ResolveStart`
  1567. *
  1568. * @publicApi
  1569. */
  1570. class ChildActivationStart {
  1571. constructor(
  1572. /** @docsNotRequired */
  1573. snapshot) {
  1574. this.snapshot = snapshot;
  1575. this.type = 11 /* EventType.ChildActivationStart */;
  1576. }
  1577. toString() {
  1578. const path = this.snapshot.routeConfig && this.snapshot.routeConfig.path || '';
  1579. return `ChildActivationStart(path: '${path}')`;
  1580. }
  1581. }
  1582. /**
  1583. * An event triggered at the end of the child-activation part
  1584. * of the Resolve phase of routing.
  1585. * @see `ChildActivationStart`
  1586. * @see `ResolveStart`
  1587. * @publicApi
  1588. */
  1589. class ChildActivationEnd {
  1590. constructor(
  1591. /** @docsNotRequired */
  1592. snapshot) {
  1593. this.snapshot = snapshot;
  1594. this.type = 12 /* EventType.ChildActivationEnd */;
  1595. }
  1596. toString() {
  1597. const path = this.snapshot.routeConfig && this.snapshot.routeConfig.path || '';
  1598. return `ChildActivationEnd(path: '${path}')`;
  1599. }
  1600. }
  1601. /**
  1602. * An event triggered at the start of the activation part
  1603. * of the Resolve phase of routing.
  1604. * @see `ActivationEnd`
  1605. * @see `ResolveStart`
  1606. *
  1607. * @publicApi
  1608. */
  1609. class ActivationStart {
  1610. constructor(
  1611. /** @docsNotRequired */
  1612. snapshot) {
  1613. this.snapshot = snapshot;
  1614. this.type = 13 /* EventType.ActivationStart */;
  1615. }
  1616. toString() {
  1617. const path = this.snapshot.routeConfig && this.snapshot.routeConfig.path || '';
  1618. return `ActivationStart(path: '${path}')`;
  1619. }
  1620. }
  1621. /**
  1622. * An event triggered at the end of the activation part
  1623. * of the Resolve phase of routing.
  1624. * @see `ActivationStart`
  1625. * @see `ResolveStart`
  1626. *
  1627. * @publicApi
  1628. */
  1629. class ActivationEnd {
  1630. constructor(
  1631. /** @docsNotRequired */
  1632. snapshot) {
  1633. this.snapshot = snapshot;
  1634. this.type = 14 /* EventType.ActivationEnd */;
  1635. }
  1636. toString() {
  1637. const path = this.snapshot.routeConfig && this.snapshot.routeConfig.path || '';
  1638. return `ActivationEnd(path: '${path}')`;
  1639. }
  1640. }
  1641. /**
  1642. * An event triggered by scrolling.
  1643. *
  1644. * @publicApi
  1645. */
  1646. class Scroll {
  1647. constructor(
  1648. /** @docsNotRequired */
  1649. routerEvent,
  1650. /** @docsNotRequired */
  1651. position,
  1652. /** @docsNotRequired */
  1653. anchor) {
  1654. this.routerEvent = routerEvent;
  1655. this.position = position;
  1656. this.anchor = anchor;
  1657. this.type = 15 /* EventType.Scroll */;
  1658. }
  1659. toString() {
  1660. const pos = this.position ? `${this.position[0]}, ${this.position[1]}` : null;
  1661. return `Scroll(anchor: '${this.anchor}', position: '${pos}')`;
  1662. }
  1663. }
  1664. function stringifyEvent(routerEvent) {
  1665. switch (routerEvent.type) {
  1666. case 14 /* EventType.ActivationEnd */:
  1667. return `ActivationEnd(path: '${routerEvent.snapshot.routeConfig?.path || ''}')`;
  1668. case 13 /* EventType.ActivationStart */:
  1669. return `ActivationStart(path: '${routerEvent.snapshot.routeConfig?.path || ''}')`;
  1670. case 12 /* EventType.ChildActivationEnd */:
  1671. return `ChildActivationEnd(path: '${routerEvent.snapshot.routeConfig?.path || ''}')`;
  1672. case 11 /* EventType.ChildActivationStart */:
  1673. return `ChildActivationStart(path: '${routerEvent.snapshot.routeConfig?.path || ''}')`;
  1674. case 8 /* EventType.GuardsCheckEnd */:
  1675. return `GuardsCheckEnd(id: ${routerEvent.id}, url: '${routerEvent.url}', urlAfterRedirects: '${routerEvent.urlAfterRedirects}', state: ${routerEvent.state}, shouldActivate: ${routerEvent.shouldActivate})`;
  1676. case 7 /* EventType.GuardsCheckStart */:
  1677. return `GuardsCheckStart(id: ${routerEvent.id}, url: '${routerEvent.url}', urlAfterRedirects: '${routerEvent.urlAfterRedirects}', state: ${routerEvent.state})`;
  1678. case 2 /* EventType.NavigationCancel */:
  1679. return `NavigationCancel(id: ${routerEvent.id}, url: '${routerEvent.url}')`;
  1680. case 16 /* EventType.NavigationSkipped */:
  1681. return `NavigationSkipped(id: ${routerEvent.id}, url: '${routerEvent.url}')`;
  1682. case 1 /* EventType.NavigationEnd */:
  1683. return `NavigationEnd(id: ${routerEvent.id}, url: '${routerEvent.url}', urlAfterRedirects: '${routerEvent.urlAfterRedirects}')`;
  1684. case 3 /* EventType.NavigationError */:
  1685. return `NavigationError(id: ${routerEvent.id}, url: '${routerEvent.url}', error: ${routerEvent.error})`;
  1686. case 0 /* EventType.NavigationStart */:
  1687. return `NavigationStart(id: ${routerEvent.id}, url: '${routerEvent.url}')`;
  1688. case 6 /* EventType.ResolveEnd */:
  1689. return `ResolveEnd(id: ${routerEvent.id}, url: '${routerEvent.url}', urlAfterRedirects: '${routerEvent.urlAfterRedirects}', state: ${routerEvent.state})`;
  1690. case 5 /* EventType.ResolveStart */:
  1691. return `ResolveStart(id: ${routerEvent.id}, url: '${routerEvent.url}', urlAfterRedirects: '${routerEvent.urlAfterRedirects}', state: ${routerEvent.state})`;
  1692. case 10 /* EventType.RouteConfigLoadEnd */:
  1693. return `RouteConfigLoadEnd(path: ${routerEvent.route.path})`;
  1694. case 9 /* EventType.RouteConfigLoadStart */:
  1695. return `RouteConfigLoadStart(path: ${routerEvent.route.path})`;
  1696. case 4 /* EventType.RoutesRecognized */:
  1697. return `RoutesRecognized(id: ${routerEvent.id}, url: '${routerEvent.url}', urlAfterRedirects: '${routerEvent.urlAfterRedirects}', state: ${routerEvent.state})`;
  1698. case 15 /* EventType.Scroll */:
  1699. const pos = routerEvent.position ? `${routerEvent.position[0]}, ${routerEvent.position[1]}` : null;
  1700. return `Scroll(anchor: '${routerEvent.anchor}', position: '${pos}')`;
  1701. }
  1702. }
  1703. /**
  1704. * Store contextual information about a `RouterOutlet`
  1705. *
  1706. * @publicApi
  1707. */
  1708. class OutletContext {
  1709. constructor() {
  1710. this.outlet = null;
  1711. this.route = null;
  1712. this.injector = null;
  1713. this.children = new ChildrenOutletContexts();
  1714. this.attachRef = null;
  1715. }
  1716. }
  1717. /**
  1718. * Store contextual information about the children (= nested) `RouterOutlet`
  1719. *
  1720. * @publicApi
  1721. */
  1722. class ChildrenOutletContexts {
  1723. constructor() {
  1724. // contexts for child outlets, by name.
  1725. this.contexts = new Map();
  1726. }
  1727. /** Called when a `RouterOutlet` directive is instantiated */
  1728. onChildOutletCreated(childName, outlet) {
  1729. const context = this.getOrCreateContext(childName);
  1730. context.outlet = outlet;
  1731. this.contexts.set(childName, context);
  1732. }
  1733. /**
  1734. * Called when a `RouterOutlet` directive is destroyed.
  1735. * We need to keep the context as the outlet could be destroyed inside a NgIf and might be
  1736. * re-created later.
  1737. */
  1738. onChildOutletDestroyed(childName) {
  1739. const context = this.getContext(childName);
  1740. if (context) {
  1741. context.outlet = null;
  1742. context.attachRef = null;
  1743. }
  1744. }
  1745. /**
  1746. * Called when the corresponding route is deactivated during navigation.
  1747. * Because the component get destroyed, all children outlet are destroyed.
  1748. */
  1749. onOutletDeactivated() {
  1750. const contexts = this.contexts;
  1751. this.contexts = new Map();
  1752. return contexts;
  1753. }
  1754. onOutletReAttached(contexts) {
  1755. this.contexts = contexts;
  1756. }
  1757. getOrCreateContext(childName) {
  1758. let context = this.getContext(childName);
  1759. if (!context) {
  1760. context = new OutletContext();
  1761. this.contexts.set(childName, context);
  1762. }
  1763. return context;
  1764. }
  1765. getContext(childName) {
  1766. return this.contexts.get(childName) || null;
  1767. }
  1768. static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "16.0.4", ngImport: i0, type: ChildrenOutletContexts, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
  1769. static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "16.0.4", ngImport: i0, type: ChildrenOutletContexts, providedIn: 'root' }); }
  1770. }
  1771. i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "16.0.4", ngImport: i0, type: ChildrenOutletContexts, decorators: [{
  1772. type: Injectable,
  1773. args: [{ providedIn: 'root' }]
  1774. }] });
  1775. class Tree {
  1776. constructor(root) {
  1777. this._root = root;
  1778. }
  1779. get root() {
  1780. return this._root.value;
  1781. }
  1782. /**
  1783. * @internal
  1784. */
  1785. parent(t) {
  1786. const p = this.pathFromRoot(t);
  1787. return p.length > 1 ? p[p.length - 2] : null;
  1788. }
  1789. /**
  1790. * @internal
  1791. */
  1792. children(t) {
  1793. const n = findNode(t, this._root);
  1794. return n ? n.children.map(t => t.value) : [];
  1795. }
  1796. /**
  1797. * @internal
  1798. */
  1799. firstChild(t) {
  1800. const n = findNode(t, this._root);
  1801. return n && n.children.length > 0 ? n.children[0].value : null;
  1802. }
  1803. /**
  1804. * @internal
  1805. */
  1806. siblings(t) {
  1807. const p = findPath(t, this._root);
  1808. if (p.length < 2)
  1809. return [];
  1810. const c = p[p.length - 2].children.map(c => c.value);
  1811. return c.filter(cc => cc !== t);
  1812. }
  1813. /**
  1814. * @internal
  1815. */
  1816. pathFromRoot(t) {
  1817. return findPath(t, this._root).map(s => s.value);
  1818. }
  1819. }
  1820. // DFS for the node matching the value
  1821. function findNode(value, node) {
  1822. if (value === node.value)
  1823. return node;
  1824. for (const child of node.children) {
  1825. const node = findNode(value, child);
  1826. if (node)
  1827. return node;
  1828. }
  1829. return null;
  1830. }
  1831. // Return the path to the node with the given value using DFS
  1832. function findPath(value, node) {
  1833. if (value === node.value)
  1834. return [node];
  1835. for (const child of node.children) {
  1836. const path = findPath(value, child);
  1837. if (path.length) {
  1838. path.unshift(node);
  1839. return path;
  1840. }
  1841. }
  1842. return [];
  1843. }
  1844. class TreeNode {
  1845. constructor(value, children) {
  1846. this.value = value;
  1847. this.children = children;
  1848. }
  1849. toString() {
  1850. return `TreeNode(${this.value})`;
  1851. }
  1852. }
  1853. // Return the list of T indexed by outlet name
  1854. function nodeChildrenAsMap(node) {
  1855. const map = {};
  1856. if (node) {
  1857. node.children.forEach(child => map[child.value.outlet] = child);
  1858. }
  1859. return map;
  1860. }
  1861. /**
  1862. * Represents the state of the router as a tree of activated routes.
  1863. *
  1864. * @usageNotes
  1865. *
  1866. * Every node in the route tree is an `ActivatedRoute` instance
  1867. * that knows about the "consumed" URL segments, the extracted parameters,
  1868. * and the resolved data.
  1869. * Use the `ActivatedRoute` properties to traverse the tree from any node.
  1870. *
  1871. * The following fragment shows how a component gets the root node
  1872. * of the current state to establish its own route tree:
  1873. *
  1874. * ```
  1875. * @Component({templateUrl:'template.html'})
  1876. * class MyComponent {
  1877. * constructor(router: Router) {
  1878. * const state: RouterState = router.routerState;
  1879. * const root: ActivatedRoute = state.root;
  1880. * const child = root.firstChild;
  1881. * const id: Observable<string> = child.params.map(p => p.id);
  1882. * //...
  1883. * }
  1884. * }
  1885. * ```
  1886. *
  1887. * @see `ActivatedRoute`
  1888. * @see [Getting route information](guide/router#getting-route-information)
  1889. *
  1890. * @publicApi
  1891. */
  1892. class RouterState extends Tree {
  1893. /** @internal */
  1894. constructor(root,
  1895. /** The current snapshot of the router state */
  1896. snapshot) {
  1897. super(root);
  1898. this.snapshot = snapshot;
  1899. setRouterState(this, root);
  1900. }
  1901. toString() {
  1902. return this.snapshot.toString();
  1903. }
  1904. }
  1905. function createEmptyState(urlTree, rootComponent) {
  1906. const snapshot = createEmptyStateSnapshot(urlTree, rootComponent);
  1907. const emptyUrl = new BehaviorSubject([new UrlSegment('', {})]);
  1908. const emptyParams = new BehaviorSubject({});
  1909. const emptyData = new BehaviorSubject({});
  1910. const emptyQueryParams = new BehaviorSubject({});
  1911. const fragment = new BehaviorSubject('');
  1912. const activated = new ActivatedRoute(emptyUrl, emptyParams, emptyQueryParams, fragment, emptyData, PRIMARY_OUTLET, rootComponent, snapshot.root);
  1913. activated.snapshot = snapshot.root;
  1914. return new RouterState(new TreeNode(activated, []), snapshot);
  1915. }
  1916. function createEmptyStateSnapshot(urlTree, rootComponent) {
  1917. const emptyParams = {};
  1918. const emptyData = {};
  1919. const emptyQueryParams = {};
  1920. const fragment = '';
  1921. const activated = new ActivatedRouteSnapshot([], emptyParams, emptyQueryParams, fragment, emptyData, PRIMARY_OUTLET, rootComponent, null, {});
  1922. return new RouterStateSnapshot('', new TreeNode(activated, []));
  1923. }
  1924. /**
  1925. * Provides access to information about a route associated with a component
  1926. * that is loaded in an outlet.
  1927. * Use to traverse the `RouterState` tree and extract information from nodes.
  1928. *
  1929. * The following example shows how to construct a component using information from a
  1930. * currently activated route.
  1931. *
  1932. * Note: the observables in this class only emit when the current and previous values differ based
  1933. * on shallow equality. For example, changing deeply nested properties in resolved `data` will not
  1934. * cause the `ActivatedRoute.data` `Observable` to emit a new value.
  1935. *
  1936. * {@example router/activated-route/module.ts region="activated-route"
  1937. * header="activated-route.component.ts"}
  1938. *
  1939. * @see [Getting route information](guide/router#getting-route-information)
  1940. *
  1941. * @publicApi
  1942. */
  1943. class ActivatedRoute {
  1944. /** @internal */
  1945. constructor(
  1946. /** @internal */
  1947. urlSubject,
  1948. /** @internal */
  1949. paramsSubject,
  1950. /** @internal */
  1951. queryParamsSubject,
  1952. /** @internal */
  1953. fragmentSubject,
  1954. /** @internal */
  1955. dataSubject,
  1956. /** The outlet name of the route, a constant. */
  1957. outlet,
  1958. /** The component of the route, a constant. */
  1959. component, futureSnapshot) {
  1960. this.urlSubject = urlSubject;
  1961. this.paramsSubject = paramsSubject;
  1962. this.queryParamsSubject = queryParamsSubject;
  1963. this.fragmentSubject = fragmentSubject;
  1964. this.dataSubject = dataSubject;
  1965. this.outlet = outlet;
  1966. this.component = component;
  1967. this._futureSnapshot = futureSnapshot;
  1968. this.title = this.dataSubject?.pipe(map((d) => d[RouteTitleKey])) ?? of(undefined);
  1969. // TODO(atscott): Verify that these can be changed to `.asObservable()` with TGP.
  1970. this.url = urlSubject;
  1971. this.params = paramsSubject;
  1972. this.queryParams = queryParamsSubject;
  1973. this.fragment = fragmentSubject;
  1974. this.data = dataSubject;
  1975. }
  1976. /** The configuration used to match this route. */
  1977. get routeConfig() {
  1978. return this._futureSnapshot.routeConfig;
  1979. }
  1980. /** The root of the router state. */
  1981. get root() {
  1982. return this._routerState.root;
  1983. }
  1984. /** The parent of this route in the router state tree. */
  1985. get parent() {
  1986. return this._routerState.parent(this);
  1987. }
  1988. /** The first child of this route in the router state tree. */
  1989. get firstChild() {
  1990. return this._routerState.firstChild(this);
  1991. }
  1992. /** The children of this route in the router state tree. */
  1993. get children() {
  1994. return this._routerState.children(this);
  1995. }
  1996. /** The path from the root of the router state tree to this route. */
  1997. get pathFromRoot() {
  1998. return this._routerState.pathFromRoot(this);
  1999. }
  2000. /**
  2001. * An Observable that contains a map of the required and optional parameters
  2002. * specific to the route.
  2003. * The map supports retrieving single and multiple values from the same parameter.
  2004. */
  2005. get paramMap() {
  2006. if (!this._paramMap) {
  2007. this._paramMap = this.params.pipe(map((p) => convertToParamMap(p)));
  2008. }
  2009. return this._paramMap;
  2010. }
  2011. /**
  2012. * An Observable that contains a map of the query parameters available to all routes.
  2013. * The map supports retrieving single and multiple values from the query parameter.
  2014. */
  2015. get queryParamMap() {
  2016. if (!this._queryParamMap) {
  2017. this._queryParamMap =
  2018. this.queryParams.pipe(map((p) => convertToParamMap(p)));
  2019. }
  2020. return this._queryParamMap;
  2021. }
  2022. toString() {
  2023. return this.snapshot ? this.snapshot.toString() : `Future(${this._futureSnapshot})`;
  2024. }
  2025. }
  2026. /**
  2027. * Returns the inherited params, data, and resolve for a given route.
  2028. * By default, this only inherits values up to the nearest path-less or component-less route.
  2029. * @internal
  2030. */
  2031. function inheritedParamsDataResolve(route, paramsInheritanceStrategy = 'emptyOnly') {
  2032. const pathFromRoot = route.pathFromRoot;
  2033. let inheritingStartingFrom = 0;
  2034. if (paramsInheritanceStrategy !== 'always') {
  2035. inheritingStartingFrom = pathFromRoot.length - 1;
  2036. while (inheritingStartingFrom >= 1) {
  2037. const current = pathFromRoot[inheritingStartingFrom];
  2038. const parent = pathFromRoot[inheritingStartingFrom - 1];
  2039. // current route is an empty path => inherits its parent's params and data
  2040. if (current.routeConfig && current.routeConfig.path === '') {
  2041. inheritingStartingFrom--;
  2042. // parent is componentless => current route should inherit its params and data
  2043. }
  2044. else if (!parent.component) {
  2045. inheritingStartingFrom--;
  2046. }
  2047. else {
  2048. break;
  2049. }
  2050. }
  2051. }
  2052. return flattenInherited(pathFromRoot.slice(inheritingStartingFrom));
  2053. }
  2054. /** @internal */
  2055. function flattenInherited(pathFromRoot) {
  2056. return pathFromRoot.reduce((res, curr) => {
  2057. const params = { ...res.params, ...curr.params };
  2058. const data = { ...res.data, ...curr.data };
  2059. const resolve = { ...curr.data, ...res.resolve, ...curr.routeConfig?.data, ...curr._resolvedData };
  2060. return { params, data, resolve };
  2061. }, { params: {}, data: {}, resolve: {} });
  2062. }
  2063. /**
  2064. * @description
  2065. *
  2066. * Contains the information about a route associated with a component loaded in an
  2067. * outlet at a particular moment in time. ActivatedRouteSnapshot can also be used to
  2068. * traverse the router state tree.
  2069. *
  2070. * The following example initializes a component with route information extracted
  2071. * from the snapshot of the root node at the time of creation.
  2072. *
  2073. * ```
  2074. * @Component({templateUrl:'./my-component.html'})
  2075. * class MyComponent {
  2076. * constructor(route: ActivatedRoute) {
  2077. * const id: string = route.snapshot.params.id;
  2078. * const url: string = route.snapshot.url.join('');
  2079. * const user = route.snapshot.data.user;
  2080. * }
  2081. * }
  2082. * ```
  2083. *
  2084. * @publicApi
  2085. */
  2086. class ActivatedRouteSnapshot {
  2087. /** The resolved route title */
  2088. get title() {
  2089. // Note: This _must_ be a getter because the data is mutated in the resolvers. Title will not be
  2090. // available at the time of class instantiation.
  2091. return this.data?.[RouteTitleKey];
  2092. }
  2093. /** @internal */
  2094. constructor(
  2095. /** The URL segments matched by this route */
  2096. url,
  2097. /**
  2098. * The matrix parameters scoped to this route.
  2099. *
  2100. * You can compute all params (or data) in the router state or to get params outside
  2101. * of an activated component by traversing the `RouterState` tree as in the following
  2102. * example:
  2103. * ```
  2104. * collectRouteParams(router: Router) {
  2105. * let params = {};
  2106. * let stack: ActivatedRouteSnapshot[] = [router.routerState.snapshot.root];
  2107. * while (stack.length > 0) {
  2108. * const route = stack.pop()!;
  2109. * params = {...params, ...route.params};
  2110. * stack.push(...route.children);
  2111. * }
  2112. * return params;
  2113. * }
  2114. * ```
  2115. */
  2116. params,
  2117. /** The query parameters shared by all the routes */
  2118. queryParams,
  2119. /** The URL fragment shared by all the routes */
  2120. fragment,
  2121. /** The static and resolved data of this route */
  2122. data,
  2123. /** The outlet name of the route */
  2124. outlet,
  2125. /** The component of the route */
  2126. component, routeConfig, resolve) {
  2127. this.url = url;
  2128. this.params = params;
  2129. this.queryParams = queryParams;
  2130. this.fragment = fragment;
  2131. this.data = data;
  2132. this.outlet = outlet;
  2133. this.component = component;
  2134. this.routeConfig = routeConfig;
  2135. this._resolve = resolve;
  2136. }
  2137. /** The root of the router state */
  2138. get root() {
  2139. return this._routerState.root;
  2140. }
  2141. /** The parent of this route in the router state tree */
  2142. get parent() {
  2143. return this._routerState.parent(this);
  2144. }
  2145. /** The first child of this route in the router state tree */
  2146. get firstChild() {
  2147. return this._routerState.firstChild(this);
  2148. }
  2149. /** The children of this route in the router state tree */
  2150. get children() {
  2151. return this._routerState.children(this);
  2152. }
  2153. /** The path from the root of the router state tree to this route */
  2154. get pathFromRoot() {
  2155. return this._routerState.pathFromRoot(this);
  2156. }
  2157. get paramMap() {
  2158. if (!this._paramMap) {
  2159. this._paramMap = convertToParamMap(this.params);
  2160. }
  2161. return this._paramMap;
  2162. }
  2163. get queryParamMap() {
  2164. if (!this._queryParamMap) {
  2165. this._queryParamMap = convertToParamMap(this.queryParams);
  2166. }
  2167. return this._queryParamMap;
  2168. }
  2169. toString() {
  2170. const url = this.url.map(segment => segment.toString()).join('/');
  2171. const matched = this.routeConfig ? this.routeConfig.path : '';
  2172. return `Route(url:'${url}', path:'${matched}')`;
  2173. }
  2174. }
  2175. /**
  2176. * @description
  2177. *
  2178. * Represents the state of the router at a moment in time.
  2179. *
  2180. * This is a tree of activated route snapshots. Every node in this tree knows about
  2181. * the "consumed" URL segments, the extracted parameters, and the resolved data.
  2182. *
  2183. * The following example shows how a component is initialized with information
  2184. * from the snapshot of the root node's state at the time of creation.
  2185. *
  2186. * ```
  2187. * @Component({templateUrl:'template.html'})
  2188. * class MyComponent {
  2189. * constructor(router: Router) {
  2190. * const state: RouterState = router.routerState;
  2191. * const snapshot: RouterStateSnapshot = state.snapshot;
  2192. * const root: ActivatedRouteSnapshot = snapshot.root;
  2193. * const child = root.firstChild;
  2194. * const id: Observable<string> = child.params.map(p => p.id);
  2195. * //...
  2196. * }
  2197. * }
  2198. * ```
  2199. *
  2200. * @publicApi
  2201. */
  2202. class RouterStateSnapshot extends Tree {
  2203. /** @internal */
  2204. constructor(
  2205. /** The url from which this snapshot was created */
  2206. url, root) {
  2207. super(root);
  2208. this.url = url;
  2209. setRouterState(this, root);
  2210. }
  2211. toString() {
  2212. return serializeNode(this._root);
  2213. }
  2214. }
  2215. function setRouterState(state, node) {
  2216. node.value._routerState = state;
  2217. node.children.forEach(c => setRouterState(state, c));
  2218. }
  2219. function serializeNode(node) {
  2220. const c = node.children.length > 0 ? ` { ${node.children.map(serializeNode).join(', ')} } ` : '';
  2221. return `${node.value}${c}`;
  2222. }
  2223. /**
  2224. * The expectation is that the activate route is created with the right set of parameters.
  2225. * So we push new values into the observables only when they are not the initial values.
  2226. * And we detect that by checking if the snapshot field is set.
  2227. */
  2228. function advanceActivatedRoute(route) {
  2229. if (route.snapshot) {
  2230. const currentSnapshot = route.snapshot;
  2231. const nextSnapshot = route._futureSnapshot;
  2232. route.snapshot = nextSnapshot;
  2233. if (!shallowEqual(currentSnapshot.queryParams, nextSnapshot.queryParams)) {
  2234. route.queryParamsSubject.next(nextSnapshot.queryParams);
  2235. }
  2236. if (currentSnapshot.fragment !== nextSnapshot.fragment) {
  2237. route.fragmentSubject.next(nextSnapshot.fragment);
  2238. }
  2239. if (!shallowEqual(currentSnapshot.params, nextSnapshot.params)) {
  2240. route.paramsSubject.next(nextSnapshot.params);
  2241. }
  2242. if (!shallowEqualArrays(currentSnapshot.url, nextSnapshot.url)) {
  2243. route.urlSubject.next(nextSnapshot.url);
  2244. }
  2245. if (!shallowEqual(currentSnapshot.data, nextSnapshot.data)) {
  2246. route.dataSubject.next(nextSnapshot.data);
  2247. }
  2248. }
  2249. else {
  2250. route.snapshot = route._futureSnapshot;
  2251. // this is for resolved data
  2252. route.dataSubject.next(route._futureSnapshot.data);
  2253. }
  2254. }
  2255. function equalParamsAndUrlSegments(a, b) {
  2256. const equalUrlParams = shallowEqual(a.params, b.params) && equalSegments(a.url, b.url);
  2257. const parentsMismatch = !a.parent !== !b.parent;
  2258. return equalUrlParams && !parentsMismatch &&
  2259. (!a.parent || equalParamsAndUrlSegments(a.parent, b.parent));
  2260. }
  2261. /**
  2262. * @description
  2263. *
  2264. * Acts as a placeholder that Angular dynamically fills based on the current router state.
  2265. *
  2266. * Each outlet can have a unique name, determined by the optional `name` attribute.
  2267. * The name cannot be set or changed dynamically. If not set, default value is "primary".
  2268. *
  2269. * ```
  2270. * <router-outlet></router-outlet>
  2271. * <router-outlet name='left'></router-outlet>
  2272. * <router-outlet name='right'></router-outlet>
  2273. * ```
  2274. *
  2275. * Named outlets can be the targets of secondary routes.
  2276. * The `Route` object for a secondary route has an `outlet` property to identify the target outlet:
  2277. *
  2278. * `{path: <base-path>, component: <component>, outlet: <target_outlet_name>}`
  2279. *
  2280. * Using named outlets and secondary routes, you can target multiple outlets in
  2281. * the same `RouterLink` directive.
  2282. *
  2283. * The router keeps track of separate branches in a navigation tree for each named outlet and
  2284. * generates a representation of that tree in the URL.
  2285. * The URL for a secondary route uses the following syntax to specify both the primary and secondary
  2286. * routes at the same time:
  2287. *
  2288. * `http://base-path/primary-route-path(outlet-name:route-path)`
  2289. *
  2290. * A router outlet emits an activate event when a new component is instantiated,
  2291. * deactivate event when a component is destroyed.
  2292. * An attached event emits when the `RouteReuseStrategy` instructs the outlet to reattach the
  2293. * subtree, and the detached event emits when the `RouteReuseStrategy` instructs the outlet to
  2294. * detach the subtree.
  2295. *
  2296. * ```
  2297. * <router-outlet
  2298. * (activate)='onActivate($event)'
  2299. * (deactivate)='onDeactivate($event)'
  2300. * (attach)='onAttach($event)'
  2301. * (detach)='onDetach($event)'></router-outlet>
  2302. * ```
  2303. *
  2304. * @see [Routing tutorial](guide/router-tutorial-toh#named-outlets "Example of a named
  2305. * outlet and secondary route configuration").
  2306. * @see `RouterLink`
  2307. * @see `Route`
  2308. * @ngModule RouterModule
  2309. *
  2310. * @publicApi
  2311. */
  2312. class RouterOutlet {
  2313. constructor() {
  2314. this.activated = null;
  2315. this._activatedRoute = null;
  2316. /**
  2317. * The name of the outlet
  2318. *
  2319. * @see [named outlets](guide/router-tutorial-toh#displaying-multiple-routes-in-named-outlets)
  2320. */
  2321. this.name = PRIMARY_OUTLET;
  2322. this.activateEvents = new EventEmitter();
  2323. this.deactivateEvents = new EventEmitter();
  2324. /**
  2325. * Emits an attached component instance when the `RouteReuseStrategy` instructs to re-attach a
  2326. * previously detached subtree.
  2327. **/
  2328. this.attachEvents = new EventEmitter();
  2329. /**
  2330. * Emits a detached component instance when the `RouteReuseStrategy` instructs to detach the
  2331. * subtree.
  2332. */
  2333. this.detachEvents = new EventEmitter();
  2334. this.parentContexts = inject(ChildrenOutletContexts);
  2335. this.location = inject(ViewContainerRef);
  2336. this.changeDetector = inject(ChangeDetectorRef);
  2337. this.environmentInjector = inject(EnvironmentInjector);
  2338. this.inputBinder = inject(INPUT_BINDER, { optional: true });
  2339. /** @nodoc */
  2340. this.supportsBindingToComponentInputs = true;
  2341. }
  2342. /** @internal */
  2343. get activatedComponentRef() {
  2344. return this.activated;
  2345. }
  2346. /** @nodoc */
  2347. ngOnChanges(changes) {
  2348. if (changes['name']) {
  2349. const { firstChange, previousValue } = changes['name'];
  2350. if (firstChange) {
  2351. // The first change is handled by ngOnInit. Because ngOnChanges doesn't get called when no
  2352. // input is set at all, we need to centrally handle the first change there.
  2353. return;
  2354. }
  2355. // unregister with the old name
  2356. if (this.isTrackedInParentContexts(previousValue)) {
  2357. this.deactivate();
  2358. this.parentContexts.onChildOutletDestroyed(previousValue);
  2359. }
  2360. // register the new name
  2361. this.initializeOutletWithName();
  2362. }
  2363. }
  2364. /** @nodoc */
  2365. ngOnDestroy() {
  2366. // Ensure that the registered outlet is this one before removing it on the context.
  2367. if (this.isTrackedInParentContexts(this.name)) {
  2368. this.parentContexts.onChildOutletDestroyed(this.name);
  2369. }
  2370. this.inputBinder?.unsubscribeFromRouteData(this);
  2371. }
  2372. isTrackedInParentContexts(outletName) {
  2373. return this.parentContexts.getContext(outletName)?.outlet === this;
  2374. }
  2375. /** @nodoc */
  2376. ngOnInit() {
  2377. this.initializeOutletWithName();
  2378. }
  2379. initializeOutletWithName() {
  2380. this.parentContexts.onChildOutletCreated(this.name, this);
  2381. if (this.activated) {
  2382. return;
  2383. }
  2384. // If the outlet was not instantiated at the time the route got activated we need to populate
  2385. // the outlet when it is initialized (ie inside a NgIf)
  2386. const context = this.parentContexts.getContext(this.name);
  2387. if (context?.route) {
  2388. if (context.attachRef) {
  2389. // `attachRef` is populated when there is an existing component to mount
  2390. this.attach(context.attachRef, context.route);
  2391. }
  2392. else {
  2393. // otherwise the component defined in the configuration is created
  2394. this.activateWith(context.route, context.injector);
  2395. }
  2396. }
  2397. }
  2398. get isActivated() {
  2399. return !!this.activated;
  2400. }
  2401. /**
  2402. * @returns The currently activated component instance.
  2403. * @throws An error if the outlet is not activated.
  2404. */
  2405. get component() {
  2406. if (!this.activated)
  2407. throw new ɵRuntimeError(4012 /* RuntimeErrorCode.OUTLET_NOT_ACTIVATED */, (typeof ngDevMode === 'undefined' || ngDevMode) && 'Outlet is not activated');
  2408. return this.activated.instance;
  2409. }
  2410. get activatedRoute() {
  2411. if (!this.activated)
  2412. throw new ɵRuntimeError(4012 /* RuntimeErrorCode.OUTLET_NOT_ACTIVATED */, (typeof ngDevMode === 'undefined' || ngDevMode) && 'Outlet is not activated');
  2413. return this._activatedRoute;
  2414. }
  2415. get activatedRouteData() {
  2416. if (this._activatedRoute) {
  2417. return this._activatedRoute.snapshot.data;
  2418. }
  2419. return {};
  2420. }
  2421. /**
  2422. * Called when the `RouteReuseStrategy` instructs to detach the subtree
  2423. */
  2424. detach() {
  2425. if (!this.activated)
  2426. throw new ɵRuntimeError(4012 /* RuntimeErrorCode.OUTLET_NOT_ACTIVATED */, (typeof ngDevMode === 'undefined' || ngDevMode) && 'Outlet is not activated');
  2427. this.location.detach();
  2428. const cmp = this.activated;
  2429. this.activated = null;
  2430. this._activatedRoute = null;
  2431. this.detachEvents.emit(cmp.instance);
  2432. return cmp;
  2433. }
  2434. /**
  2435. * Called when the `RouteReuseStrategy` instructs to re-attach a previously detached subtree
  2436. */
  2437. attach(ref, activatedRoute) {
  2438. this.activated = ref;
  2439. this._activatedRoute = activatedRoute;
  2440. this.location.insert(ref.hostView);
  2441. this.inputBinder?.bindActivatedRouteToOutletComponent(this);
  2442. this.attachEvents.emit(ref.instance);
  2443. }
  2444. deactivate() {
  2445. if (this.activated) {
  2446. const c = this.component;
  2447. this.activated.destroy();
  2448. this.activated = null;
  2449. this._activatedRoute = null;
  2450. this.deactivateEvents.emit(c);
  2451. }
  2452. }
  2453. activateWith(activatedRoute, environmentInjector) {
  2454. if (this.isActivated) {
  2455. throw new ɵRuntimeError(4013 /* RuntimeErrorCode.OUTLET_ALREADY_ACTIVATED */, (typeof ngDevMode === 'undefined' || ngDevMode) &&
  2456. 'Cannot activate an already activated outlet');
  2457. }
  2458. this._activatedRoute = activatedRoute;
  2459. const location = this.location;
  2460. const snapshot = activatedRoute.snapshot;
  2461. const component = snapshot.component;
  2462. const childContexts = this.parentContexts.getOrCreateContext(this.name).children;
  2463. const injector = new OutletInjector(activatedRoute, childContexts, location.injector);
  2464. this.activated = location.createComponent(component, {
  2465. index: location.length,
  2466. injector,
  2467. environmentInjector: environmentInjector ?? this.environmentInjector
  2468. });
  2469. // Calling `markForCheck` to make sure we will run the change detection when the
  2470. // `RouterOutlet` is inside a `ChangeDetectionStrategy.OnPush` component.
  2471. this.changeDetector.markForCheck();
  2472. this.inputBinder?.bindActivatedRouteToOutletComponent(this);
  2473. this.activateEvents.emit(this.activated.instance);
  2474. }
  2475. static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "16.0.4", ngImport: i0, type: RouterOutlet, deps: [], target: i0.ɵɵFactoryTarget.Directive }); }
  2476. static { this.ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "14.0.0", version: "16.0.4", type: RouterOutlet, isStandalone: true, selector: "router-outlet", inputs: { name: "name" }, outputs: { activateEvents: "activate", deactivateEvents: "deactivate", attachEvents: "attach", detachEvents: "detach" }, exportAs: ["outlet"], usesOnChanges: true, ngImport: i0 }); }
  2477. }
  2478. i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "16.0.4", ngImport: i0, type: RouterOutlet, decorators: [{
  2479. type: Directive,
  2480. args: [{
  2481. selector: 'router-outlet',
  2482. exportAs: 'outlet',
  2483. standalone: true,
  2484. }]
  2485. }], propDecorators: { name: [{
  2486. type: Input
  2487. }], activateEvents: [{
  2488. type: Output,
  2489. args: ['activate']
  2490. }], deactivateEvents: [{
  2491. type: Output,
  2492. args: ['deactivate']
  2493. }], attachEvents: [{
  2494. type: Output,
  2495. args: ['attach']
  2496. }], detachEvents: [{
  2497. type: Output,
  2498. args: ['detach']
  2499. }] } });
  2500. class OutletInjector {
  2501. constructor(route, childContexts, parent) {
  2502. this.route = route;
  2503. this.childContexts = childContexts;
  2504. this.parent = parent;
  2505. }
  2506. get(token, notFoundValue) {
  2507. if (token === ActivatedRoute) {
  2508. return this.route;
  2509. }
  2510. if (token === ChildrenOutletContexts) {
  2511. return this.childContexts;
  2512. }
  2513. return this.parent.get(token, notFoundValue);
  2514. }
  2515. }
  2516. const INPUT_BINDER = new InjectionToken('');
  2517. /**
  2518. * Injectable used as a tree-shakable provider for opting in to binding router data to component
  2519. * inputs.
  2520. *
  2521. * The RouterOutlet registers itself with this service when an `ActivatedRoute` is attached or
  2522. * activated. When this happens, the service subscribes to the `ActivatedRoute` observables (params,
  2523. * queryParams, data) and sets the inputs of the component using `ComponentRef.setInput`.
  2524. * Importantly, when an input does not have an item in the route data with a matching key, this
  2525. * input is set to `undefined`. If it were not done this way, the previous information would be
  2526. * retained if the data got removed from the route (i.e. if a query parameter is removed).
  2527. *
  2528. * The `RouterOutlet` should unregister itself when destroyed via `unsubscribeFromRouteData` so that
  2529. * the subscriptions are cleaned up.
  2530. */
  2531. class RoutedComponentInputBinder {
  2532. constructor() {
  2533. this.outletDataSubscriptions = new Map;
  2534. }
  2535. bindActivatedRouteToOutletComponent(outlet) {
  2536. this.unsubscribeFromRouteData(outlet);
  2537. this.subscribeToRouteData(outlet);
  2538. }
  2539. unsubscribeFromRouteData(outlet) {
  2540. this.outletDataSubscriptions.get(outlet)?.unsubscribe();
  2541. this.outletDataSubscriptions.delete(outlet);
  2542. }
  2543. subscribeToRouteData(outlet) {
  2544. const { activatedRoute } = outlet;
  2545. const dataSubscription = combineLatest([
  2546. activatedRoute.queryParams,
  2547. activatedRoute.params,
  2548. activatedRoute.data,
  2549. ])
  2550. .pipe(switchMap(([queryParams, params, data], index) => {
  2551. data = { ...queryParams, ...params, ...data };
  2552. // Get the first result from the data subscription synchronously so it's available to
  2553. // the component as soon as possible (and doesn't require a second change detection).
  2554. if (index === 0) {
  2555. return of(data);
  2556. }
  2557. // Promise.resolve is used to avoid synchronously writing the wrong data when
  2558. // two of the Observables in the `combineLatest` stream emit one after
  2559. // another.
  2560. return Promise.resolve(data);
  2561. }))
  2562. .subscribe(data => {
  2563. // Outlet may have been deactivated or changed names to be associated with a different
  2564. // route
  2565. if (!outlet.isActivated || !outlet.activatedComponentRef ||
  2566. outlet.activatedRoute !== activatedRoute || activatedRoute.component === null) {
  2567. this.unsubscribeFromRouteData(outlet);
  2568. return;
  2569. }
  2570. const mirror = reflectComponentType(activatedRoute.component);
  2571. if (!mirror) {
  2572. this.unsubscribeFromRouteData(outlet);
  2573. return;
  2574. }
  2575. for (const { templateName } of mirror.inputs) {
  2576. outlet.activatedComponentRef.setInput(templateName, data[templateName]);
  2577. }
  2578. });
  2579. this.outletDataSubscriptions.set(outlet, dataSubscription);
  2580. }
  2581. static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "16.0.4", ngImport: i0, type: RoutedComponentInputBinder, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
  2582. static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "16.0.4", ngImport: i0, type: RoutedComponentInputBinder }); }
  2583. }
  2584. i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "16.0.4", ngImport: i0, type: RoutedComponentInputBinder, decorators: [{
  2585. type: Injectable
  2586. }] });
  2587. function createRouterState(routeReuseStrategy, curr, prevState) {
  2588. const root = createNode(routeReuseStrategy, curr._root, prevState ? prevState._root : undefined);
  2589. return new RouterState(root, curr);
  2590. }
  2591. function createNode(routeReuseStrategy, curr, prevState) {
  2592. // reuse an activated route that is currently displayed on the screen
  2593. if (prevState && routeReuseStrategy.shouldReuseRoute(curr.value, prevState.value.snapshot)) {
  2594. const value = prevState.value;
  2595. value._futureSnapshot = curr.value;
  2596. const children = createOrReuseChildren(routeReuseStrategy, curr, prevState);
  2597. return new TreeNode(value, children);
  2598. }
  2599. else {
  2600. if (routeReuseStrategy.shouldAttach(curr.value)) {
  2601. // retrieve an activated route that is used to be displayed, but is not currently displayed
  2602. const detachedRouteHandle = routeReuseStrategy.retrieve(curr.value);
  2603. if (detachedRouteHandle !== null) {
  2604. const tree = detachedRouteHandle.route;
  2605. tree.value._futureSnapshot = curr.value;
  2606. tree.children = curr.children.map(c => createNode(routeReuseStrategy, c));
  2607. return tree;
  2608. }
  2609. }
  2610. const value = createActivatedRoute(curr.value);
  2611. const children = curr.children.map(c => createNode(routeReuseStrategy, c));
  2612. return new TreeNode(value, children);
  2613. }
  2614. }
  2615. function createOrReuseChildren(routeReuseStrategy, curr, prevState) {
  2616. return curr.children.map(child => {
  2617. for (const p of prevState.children) {
  2618. if (routeReuseStrategy.shouldReuseRoute(child.value, p.value.snapshot)) {
  2619. return createNode(routeReuseStrategy, child, p);
  2620. }
  2621. }
  2622. return createNode(routeReuseStrategy, child);
  2623. });
  2624. }
  2625. function createActivatedRoute(c) {
  2626. 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);
  2627. }
  2628. const NAVIGATION_CANCELING_ERROR = 'ngNavigationCancelingError';
  2629. function redirectingNavigationError(urlSerializer, redirect) {
  2630. const { redirectTo, navigationBehaviorOptions } = isUrlTree(redirect) ? { redirectTo: redirect, navigationBehaviorOptions: undefined } : redirect;
  2631. const error = navigationCancelingError(ngDevMode && `Redirecting to "${urlSerializer.serialize(redirectTo)}"`, 0 /* NavigationCancellationCode.Redirect */, redirect);
  2632. error.url = redirectTo;
  2633. error.navigationBehaviorOptions = navigationBehaviorOptions;
  2634. return error;
  2635. }
  2636. function navigationCancelingError(message, code, redirectUrl) {
  2637. const error = new Error('NavigationCancelingError: ' + (message || ''));
  2638. error[NAVIGATION_CANCELING_ERROR] = true;
  2639. error.cancellationCode = code;
  2640. if (redirectUrl) {
  2641. error.url = redirectUrl;
  2642. }
  2643. return error;
  2644. }
  2645. function isRedirectingNavigationCancelingError$1(error) {
  2646. return isNavigationCancelingError$1(error) && isUrlTree(error.url);
  2647. }
  2648. function isNavigationCancelingError$1(error) {
  2649. return error && error[NAVIGATION_CANCELING_ERROR];
  2650. }
  2651. /**
  2652. * This component is used internally within the router to be a placeholder when an empty
  2653. * router-outlet is needed. For example, with a config such as:
  2654. *
  2655. * `{path: 'parent', outlet: 'nav', children: [...]}`
  2656. *
  2657. * In order to render, there needs to be a component on this config, which will default
  2658. * to this `EmptyOutletComponent`.
  2659. */
  2660. class ɵEmptyOutletComponent {
  2661. static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "16.0.4", ngImport: i0, type: ɵEmptyOutletComponent, deps: [], target: i0.ɵɵFactoryTarget.Component }); }
  2662. static { this.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "14.0.0", version: "16.0.4", type: ɵEmptyOutletComponent, isStandalone: true, selector: "ng-component", ngImport: i0, template: `<router-outlet></router-outlet>`, isInline: true, dependencies: [{ kind: "directive", type: RouterOutlet, selector: "router-outlet", inputs: ["name"], outputs: ["activate", "deactivate", "attach", "detach"], exportAs: ["outlet"] }] }); }
  2663. }
  2664. i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "16.0.4", ngImport: i0, type: ɵEmptyOutletComponent, decorators: [{
  2665. type: Component,
  2666. args: [{
  2667. template: `<router-outlet></router-outlet>`,
  2668. imports: [RouterOutlet],
  2669. standalone: true,
  2670. }]
  2671. }] });
  2672. /**
  2673. * Creates an `EnvironmentInjector` if the `Route` has providers and one does not already exist
  2674. * and returns the injector. Otherwise, if the `Route` does not have `providers`, returns the
  2675. * `currentInjector`.
  2676. *
  2677. * @param route The route that might have providers
  2678. * @param currentInjector The parent injector of the `Route`
  2679. */
  2680. function getOrCreateRouteInjectorIfNeeded(route, currentInjector) {
  2681. if (route.providers && !route._injector) {
  2682. route._injector =
  2683. createEnvironmentInjector(route.providers, currentInjector, `Route: ${route.path}`);
  2684. }
  2685. return route._injector ?? currentInjector;
  2686. }
  2687. function getLoadedRoutes(route) {
  2688. return route._loadedRoutes;
  2689. }
  2690. function getLoadedInjector(route) {
  2691. return route._loadedInjector;
  2692. }
  2693. function getLoadedComponent(route) {
  2694. return route._loadedComponent;
  2695. }
  2696. function getProvidersInjector(route) {
  2697. return route._injector;
  2698. }
  2699. function validateConfig(config, parentPath = '', requireStandaloneComponents = false) {
  2700. // forEach doesn't iterate undefined values
  2701. for (let i = 0; i < config.length; i++) {
  2702. const route = config[i];
  2703. const fullPath = getFullPath(parentPath, route);
  2704. validateNode(route, fullPath, requireStandaloneComponents);
  2705. }
  2706. }
  2707. function assertStandalone(fullPath, component) {
  2708. if (component && ɵisNgModule(component)) {
  2709. throw new ɵRuntimeError(4014 /* RuntimeErrorCode.INVALID_ROUTE_CONFIG */, `Invalid configuration of route '${fullPath}'. You are using 'loadComponent' with a module, ` +
  2710. `but it must be used with standalone components. Use 'loadChildren' instead.`);
  2711. }
  2712. else if (component && !isStandalone(component)) {
  2713. throw new ɵRuntimeError(4014 /* RuntimeErrorCode.INVALID_ROUTE_CONFIG */, `Invalid configuration of route '${fullPath}'. The component must be standalone.`);
  2714. }
  2715. }
  2716. function validateNode(route, fullPath, requireStandaloneComponents) {
  2717. if (typeof ngDevMode === 'undefined' || ngDevMode) {
  2718. if (!route) {
  2719. throw new ɵRuntimeError(4014 /* RuntimeErrorCode.INVALID_ROUTE_CONFIG */, `
  2720. Invalid configuration of route '${fullPath}': Encountered undefined route.
  2721. The reason might be an extra comma.
  2722. Example:
  2723. const routes: Routes = [
  2724. { path: '', redirectTo: '/dashboard', pathMatch: 'full' },
  2725. { path: 'dashboard', component: DashboardComponent },, << two commas
  2726. { path: 'detail/:id', component: HeroDetailComponent }
  2727. ];
  2728. `);
  2729. }
  2730. if (Array.isArray(route)) {
  2731. throw new ɵRuntimeError(4014 /* RuntimeErrorCode.INVALID_ROUTE_CONFIG */, `Invalid configuration of route '${fullPath}': Array cannot be specified`);
  2732. }
  2733. if (!route.redirectTo && !route.component && !route.loadComponent && !route.children &&
  2734. !route.loadChildren && (route.outlet && route.outlet !== PRIMARY_OUTLET)) {
  2735. throw new ɵRuntimeError(4014 /* RuntimeErrorCode.INVALID_ROUTE_CONFIG */, `Invalid configuration of route '${fullPath}': a componentless route without children or loadChildren cannot have a named outlet set`);
  2736. }
  2737. if (route.redirectTo && route.children) {
  2738. throw new ɵRuntimeError(4014 /* RuntimeErrorCode.INVALID_ROUTE_CONFIG */, `Invalid configuration of route '${fullPath}': redirectTo and children cannot be used together`);
  2739. }
  2740. if (route.redirectTo && route.loadChildren) {
  2741. throw new ɵRuntimeError(4014 /* RuntimeErrorCode.INVALID_ROUTE_CONFIG */, `Invalid configuration of route '${fullPath}': redirectTo and loadChildren cannot be used together`);
  2742. }
  2743. if (route.children && route.loadChildren) {
  2744. throw new ɵRuntimeError(4014 /* RuntimeErrorCode.INVALID_ROUTE_CONFIG */, `Invalid configuration of route '${fullPath}': children and loadChildren cannot be used together`);
  2745. }
  2746. if (route.redirectTo && (route.component || route.loadComponent)) {
  2747. throw new ɵRuntimeError(4014 /* RuntimeErrorCode.INVALID_ROUTE_CONFIG */, `Invalid configuration of route '${fullPath}': redirectTo and component/loadComponent cannot be used together`);
  2748. }
  2749. if (route.component && route.loadComponent) {
  2750. throw new ɵRuntimeError(4014 /* RuntimeErrorCode.INVALID_ROUTE_CONFIG */, `Invalid configuration of route '${fullPath}': component and loadComponent cannot be used together`);
  2751. }
  2752. if (route.redirectTo && route.canActivate) {
  2753. throw new ɵRuntimeError(4014 /* RuntimeErrorCode.INVALID_ROUTE_CONFIG */, `Invalid configuration of route '${fullPath}': redirectTo and canActivate cannot be used together. Redirects happen before activation ` +
  2754. `so canActivate will never be executed.`);
  2755. }
  2756. if (route.path && route.matcher) {
  2757. throw new ɵRuntimeError(4014 /* RuntimeErrorCode.INVALID_ROUTE_CONFIG */, `Invalid configuration of route '${fullPath}': path and matcher cannot be used together`);
  2758. }
  2759. if (route.redirectTo === void 0 && !route.component && !route.loadComponent &&
  2760. !route.children && !route.loadChildren) {
  2761. throw new ɵRuntimeError(4014 /* RuntimeErrorCode.INVALID_ROUTE_CONFIG */, `Invalid configuration of route '${fullPath}'. One of the following must be provided: component, loadComponent, redirectTo, children or loadChildren`);
  2762. }
  2763. if (route.path === void 0 && route.matcher === void 0) {
  2764. throw new ɵRuntimeError(4014 /* RuntimeErrorCode.INVALID_ROUTE_CONFIG */, `Invalid configuration of route '${fullPath}': routes must have either a path or a matcher specified`);
  2765. }
  2766. if (typeof route.path === 'string' && route.path.charAt(0) === '/') {
  2767. throw new ɵRuntimeError(4014 /* RuntimeErrorCode.INVALID_ROUTE_CONFIG */, `Invalid configuration of route '${fullPath}': path cannot start with a slash`);
  2768. }
  2769. if (route.path === '' && route.redirectTo !== void 0 && route.pathMatch === void 0) {
  2770. const exp = `The default value of 'pathMatch' is 'prefix', but often the intent is to use 'full'.`;
  2771. throw new ɵRuntimeError(4014 /* RuntimeErrorCode.INVALID_ROUTE_CONFIG */, `Invalid configuration of route '{path: "${fullPath}", redirectTo: "${route.redirectTo}"}': please provide 'pathMatch'. ${exp}`);
  2772. }
  2773. if (requireStandaloneComponents) {
  2774. assertStandalone(fullPath, route.component);
  2775. }
  2776. }
  2777. if (route.children) {
  2778. validateConfig(route.children, fullPath, requireStandaloneComponents);
  2779. }
  2780. }
  2781. function getFullPath(parentPath, currentRoute) {
  2782. if (!currentRoute) {
  2783. return parentPath;
  2784. }
  2785. if (!parentPath && !currentRoute.path) {
  2786. return '';
  2787. }
  2788. else if (parentPath && !currentRoute.path) {
  2789. return `${parentPath}/`;
  2790. }
  2791. else if (!parentPath && currentRoute.path) {
  2792. return currentRoute.path;
  2793. }
  2794. else {
  2795. return `${parentPath}/${currentRoute.path}`;
  2796. }
  2797. }
  2798. /**
  2799. * Makes a copy of the config and adds any default required properties.
  2800. */
  2801. function standardizeConfig(r) {
  2802. const children = r.children && r.children.map(standardizeConfig);
  2803. const c = children ? { ...r, children } : { ...r };
  2804. if ((!c.component && !c.loadComponent) && (children || c.loadChildren) &&
  2805. (c.outlet && c.outlet !== PRIMARY_OUTLET)) {
  2806. c.component = ɵEmptyOutletComponent;
  2807. }
  2808. return c;
  2809. }
  2810. /** Returns the `route.outlet` or PRIMARY_OUTLET if none exists. */
  2811. function getOutlet(route) {
  2812. return route.outlet || PRIMARY_OUTLET;
  2813. }
  2814. /**
  2815. * Sorts the `routes` such that the ones with an outlet matching `outletName` come first.
  2816. * The order of the configs is otherwise preserved.
  2817. */
  2818. function sortByMatchingOutlets(routes, outletName) {
  2819. const sortedConfig = routes.filter(r => getOutlet(r) === outletName);
  2820. sortedConfig.push(...routes.filter(r => getOutlet(r) !== outletName));
  2821. return sortedConfig;
  2822. }
  2823. /**
  2824. * Gets the first injector in the snapshot's parent tree.
  2825. *
  2826. * If the `Route` has a static list of providers, the returned injector will be the one created from
  2827. * those. If it does not exist, the returned injector may come from the parents, which may be from a
  2828. * loaded config or their static providers.
  2829. *
  2830. * Returns `null` if there is neither this nor any parents have a stored injector.
  2831. *
  2832. * Generally used for retrieving the injector to use for getting tokens for guards/resolvers and
  2833. * also used for getting the correct injector to use for creating components.
  2834. */
  2835. function getClosestRouteInjector(snapshot) {
  2836. if (!snapshot)
  2837. return null;
  2838. // If the current route has its own injector, which is created from the static providers on the
  2839. // route itself, we should use that. Otherwise, we start at the parent since we do not want to
  2840. // include the lazy loaded injector from this route.
  2841. if (snapshot.routeConfig?._injector) {
  2842. return snapshot.routeConfig._injector;
  2843. }
  2844. for (let s = snapshot.parent; s; s = s.parent) {
  2845. const route = s.routeConfig;
  2846. // Note that the order here is important. `_loadedInjector` stored on the route with
  2847. // `loadChildren: () => NgModule` so it applies to child routes with priority. The `_injector`
  2848. // is created from the static providers on that parent route, so it applies to the children as
  2849. // well, but only if there is no lazy loaded NgModuleRef injector.
  2850. if (route?._loadedInjector)
  2851. return route._loadedInjector;
  2852. if (route?._injector)
  2853. return route._injector;
  2854. }
  2855. return null;
  2856. }
  2857. let warnedAboutUnsupportedInputBinding = false;
  2858. const activateRoutes = (rootContexts, routeReuseStrategy, forwardEvent, inputBindingEnabled) => map(t => {
  2859. new ActivateRoutes(routeReuseStrategy, t.targetRouterState, t.currentRouterState, forwardEvent, inputBindingEnabled)
  2860. .activate(rootContexts);
  2861. return t;
  2862. });
  2863. class ActivateRoutes {
  2864. constructor(routeReuseStrategy, futureState, currState, forwardEvent, inputBindingEnabled) {
  2865. this.routeReuseStrategy = routeReuseStrategy;
  2866. this.futureState = futureState;
  2867. this.currState = currState;
  2868. this.forwardEvent = forwardEvent;
  2869. this.inputBindingEnabled = inputBindingEnabled;
  2870. }
  2871. activate(parentContexts) {
  2872. const futureRoot = this.futureState._root;
  2873. const currRoot = this.currState ? this.currState._root : null;
  2874. this.deactivateChildRoutes(futureRoot, currRoot, parentContexts);
  2875. advanceActivatedRoute(this.futureState.root);
  2876. this.activateChildRoutes(futureRoot, currRoot, parentContexts);
  2877. }
  2878. // De-activate the child route that are not re-used for the future state
  2879. deactivateChildRoutes(futureNode, currNode, contexts) {
  2880. const children = nodeChildrenAsMap(currNode);
  2881. // Recurse on the routes active in the future state to de-activate deeper children
  2882. futureNode.children.forEach(futureChild => {
  2883. const childOutletName = futureChild.value.outlet;
  2884. this.deactivateRoutes(futureChild, children[childOutletName], contexts);
  2885. delete children[childOutletName];
  2886. });
  2887. // De-activate the routes that will not be re-used
  2888. Object.values(children).forEach((v) => {
  2889. this.deactivateRouteAndItsChildren(v, contexts);
  2890. });
  2891. }
  2892. deactivateRoutes(futureNode, currNode, parentContext) {
  2893. const future = futureNode.value;
  2894. const curr = currNode ? currNode.value : null;
  2895. if (future === curr) {
  2896. // Reusing the node, check to see if the children need to be de-activated
  2897. if (future.component) {
  2898. // If we have a normal route, we need to go through an outlet.
  2899. const context = parentContext.getContext(future.outlet);
  2900. if (context) {
  2901. this.deactivateChildRoutes(futureNode, currNode, context.children);
  2902. }
  2903. }
  2904. else {
  2905. // if we have a componentless route, we recurse but keep the same outlet map.
  2906. this.deactivateChildRoutes(futureNode, currNode, parentContext);
  2907. }
  2908. }
  2909. else {
  2910. if (curr) {
  2911. // Deactivate the current route which will not be re-used
  2912. this.deactivateRouteAndItsChildren(currNode, parentContext);
  2913. }
  2914. }
  2915. }
  2916. deactivateRouteAndItsChildren(route, parentContexts) {
  2917. // If there is no component, the Route is never attached to an outlet (because there is no
  2918. // component to attach).
  2919. if (route.value.component && this.routeReuseStrategy.shouldDetach(route.value.snapshot)) {
  2920. this.detachAndStoreRouteSubtree(route, parentContexts);
  2921. }
  2922. else {
  2923. this.deactivateRouteAndOutlet(route, parentContexts);
  2924. }
  2925. }
  2926. detachAndStoreRouteSubtree(route, parentContexts) {
  2927. const context = parentContexts.getContext(route.value.outlet);
  2928. const contexts = context && route.value.component ? context.children : parentContexts;
  2929. const children = nodeChildrenAsMap(route);
  2930. for (const childOutlet of Object.keys(children)) {
  2931. this.deactivateRouteAndItsChildren(children[childOutlet], contexts);
  2932. }
  2933. if (context && context.outlet) {
  2934. const componentRef = context.outlet.detach();
  2935. const contexts = context.children.onOutletDeactivated();
  2936. this.routeReuseStrategy.store(route.value.snapshot, { componentRef, route, contexts });
  2937. }
  2938. }
  2939. deactivateRouteAndOutlet(route, parentContexts) {
  2940. const context = parentContexts.getContext(route.value.outlet);
  2941. // The context could be `null` if we are on a componentless route but there may still be
  2942. // children that need deactivating.
  2943. const contexts = context && route.value.component ? context.children : parentContexts;
  2944. const children = nodeChildrenAsMap(route);
  2945. for (const childOutlet of Object.keys(children)) {
  2946. this.deactivateRouteAndItsChildren(children[childOutlet], contexts);
  2947. }
  2948. if (context) {
  2949. if (context.outlet) {
  2950. // Destroy the component
  2951. context.outlet.deactivate();
  2952. // Destroy the contexts for all the outlets that were in the component
  2953. context.children.onOutletDeactivated();
  2954. }
  2955. // Clear the information about the attached component on the context but keep the reference to
  2956. // the outlet. Clear even if outlet was not yet activated to avoid activating later with old
  2957. // info
  2958. context.attachRef = null;
  2959. context.route = null;
  2960. }
  2961. }
  2962. activateChildRoutes(futureNode, currNode, contexts) {
  2963. const children = nodeChildrenAsMap(currNode);
  2964. futureNode.children.forEach(c => {
  2965. this.activateRoutes(c, children[c.value.outlet], contexts);
  2966. this.forwardEvent(new ActivationEnd(c.value.snapshot));
  2967. });
  2968. if (futureNode.children.length) {
  2969. this.forwardEvent(new ChildActivationEnd(futureNode.value.snapshot));
  2970. }
  2971. }
  2972. activateRoutes(futureNode, currNode, parentContexts) {
  2973. const future = futureNode.value;
  2974. const curr = currNode ? currNode.value : null;
  2975. advanceActivatedRoute(future);
  2976. // reusing the node
  2977. if (future === curr) {
  2978. if (future.component) {
  2979. // If we have a normal route, we need to go through an outlet.
  2980. const context = parentContexts.getOrCreateContext(future.outlet);
  2981. this.activateChildRoutes(futureNode, currNode, context.children);
  2982. }
  2983. else {
  2984. // if we have a componentless route, we recurse but keep the same outlet map.
  2985. this.activateChildRoutes(futureNode, currNode, parentContexts);
  2986. }
  2987. }
  2988. else {
  2989. if (future.component) {
  2990. // if we have a normal route, we need to place the component into the outlet and recurse.
  2991. const context = parentContexts.getOrCreateContext(future.outlet);
  2992. if (this.routeReuseStrategy.shouldAttach(future.snapshot)) {
  2993. const stored = this.routeReuseStrategy.retrieve(future.snapshot);
  2994. this.routeReuseStrategy.store(future.snapshot, null);
  2995. context.children.onOutletReAttached(stored.contexts);
  2996. context.attachRef = stored.componentRef;
  2997. context.route = stored.route.value;
  2998. if (context.outlet) {
  2999. // Attach right away when the outlet has already been instantiated
  3000. // Otherwise attach from `RouterOutlet.ngOnInit` when it is instantiated
  3001. context.outlet.attach(stored.componentRef, stored.route.value);
  3002. }
  3003. advanceActivatedRoute(stored.route.value);
  3004. this.activateChildRoutes(futureNode, null, context.children);
  3005. }
  3006. else {
  3007. const injector = getClosestRouteInjector(future.snapshot);
  3008. context.attachRef = null;
  3009. context.route = future;
  3010. context.injector = injector;
  3011. if (context.outlet) {
  3012. // Activate the outlet when it has already been instantiated
  3013. // Otherwise it will get activated from its `ngOnInit` when instantiated
  3014. context.outlet.activateWith(future, context.injector);
  3015. }
  3016. this.activateChildRoutes(futureNode, null, context.children);
  3017. }
  3018. }
  3019. else {
  3020. // if we have a componentless route, we recurse but keep the same outlet map.
  3021. this.activateChildRoutes(futureNode, null, parentContexts);
  3022. }
  3023. }
  3024. if ((typeof ngDevMode === 'undefined' || ngDevMode)) {
  3025. const context = parentContexts.getOrCreateContext(future.outlet);
  3026. const outlet = context.outlet;
  3027. if (outlet && this.inputBindingEnabled && !outlet.supportsBindingToComponentInputs &&
  3028. !warnedAboutUnsupportedInputBinding) {
  3029. console.warn(`'withComponentInputBinding' feature is enabled but ` +
  3030. `this application is using an outlet that may not support binding to component inputs.`);
  3031. warnedAboutUnsupportedInputBinding = true;
  3032. }
  3033. }
  3034. }
  3035. }
  3036. class CanActivate {
  3037. constructor(path) {
  3038. this.path = path;
  3039. this.route = this.path[this.path.length - 1];
  3040. }
  3041. }
  3042. class CanDeactivate {
  3043. constructor(component, route) {
  3044. this.component = component;
  3045. this.route = route;
  3046. }
  3047. }
  3048. function getAllRouteGuards(future, curr, parentContexts) {
  3049. const futureRoot = future._root;
  3050. const currRoot = curr ? curr._root : null;
  3051. return getChildRouteGuards(futureRoot, currRoot, parentContexts, [futureRoot.value]);
  3052. }
  3053. function getCanActivateChild(p) {
  3054. const canActivateChild = p.routeConfig ? p.routeConfig.canActivateChild : null;
  3055. if (!canActivateChild || canActivateChild.length === 0)
  3056. return null;
  3057. return { node: p, guards: canActivateChild };
  3058. }
  3059. function getTokenOrFunctionIdentity(tokenOrFunction, injector) {
  3060. const NOT_FOUND = Symbol();
  3061. const result = injector.get(tokenOrFunction, NOT_FOUND);
  3062. if (result === NOT_FOUND) {
  3063. if (typeof tokenOrFunction === 'function' && !ɵisInjectable(tokenOrFunction)) {
  3064. // We think the token is just a function so return it as-is
  3065. return tokenOrFunction;
  3066. }
  3067. else {
  3068. // This will throw the not found error
  3069. return injector.get(tokenOrFunction);
  3070. }
  3071. }
  3072. return result;
  3073. }
  3074. function getChildRouteGuards(futureNode, currNode, contexts, futurePath, checks = {
  3075. canDeactivateChecks: [],
  3076. canActivateChecks: []
  3077. }) {
  3078. const prevChildren = nodeChildrenAsMap(currNode);
  3079. // Process the children of the future route
  3080. futureNode.children.forEach(c => {
  3081. getRouteGuards(c, prevChildren[c.value.outlet], contexts, futurePath.concat([c.value]), checks);
  3082. delete prevChildren[c.value.outlet];
  3083. });
  3084. // Process any children left from the current route (not active for the future route)
  3085. Object.entries(prevChildren)
  3086. .forEach(([k, v]) => deactivateRouteAndItsChildren(v, contexts.getContext(k), checks));
  3087. return checks;
  3088. }
  3089. function getRouteGuards(futureNode, currNode, parentContexts, futurePath, checks = {
  3090. canDeactivateChecks: [],
  3091. canActivateChecks: []
  3092. }) {
  3093. const future = futureNode.value;
  3094. const curr = currNode ? currNode.value : null;
  3095. const context = parentContexts ? parentContexts.getContext(futureNode.value.outlet) : null;
  3096. // reusing the node
  3097. if (curr && future.routeConfig === curr.routeConfig) {
  3098. const shouldRun = shouldRunGuardsAndResolvers(curr, future, future.routeConfig.runGuardsAndResolvers);
  3099. if (shouldRun) {
  3100. checks.canActivateChecks.push(new CanActivate(futurePath));
  3101. }
  3102. else {
  3103. // we need to set the data
  3104. future.data = curr.data;
  3105. future._resolvedData = curr._resolvedData;
  3106. }
  3107. // If we have a component, we need to go through an outlet.
  3108. if (future.component) {
  3109. getChildRouteGuards(futureNode, currNode, context ? context.children : null, futurePath, checks);
  3110. // if we have a componentless route, we recurse but keep the same outlet map.
  3111. }
  3112. else {
  3113. getChildRouteGuards(futureNode, currNode, parentContexts, futurePath, checks);
  3114. }
  3115. if (shouldRun && context && context.outlet && context.outlet.isActivated) {
  3116. checks.canDeactivateChecks.push(new CanDeactivate(context.outlet.component, curr));
  3117. }
  3118. }
  3119. else {
  3120. if (curr) {
  3121. deactivateRouteAndItsChildren(currNode, context, checks);
  3122. }
  3123. checks.canActivateChecks.push(new CanActivate(futurePath));
  3124. // If we have a component, we need to go through an outlet.
  3125. if (future.component) {
  3126. getChildRouteGuards(futureNode, null, context ? context.children : null, futurePath, checks);
  3127. // if we have a componentless route, we recurse but keep the same outlet map.
  3128. }
  3129. else {
  3130. getChildRouteGuards(futureNode, null, parentContexts, futurePath, checks);
  3131. }
  3132. }
  3133. return checks;
  3134. }
  3135. function shouldRunGuardsAndResolvers(curr, future, mode) {
  3136. if (typeof mode === 'function') {
  3137. return mode(curr, future);
  3138. }
  3139. switch (mode) {
  3140. case 'pathParamsChange':
  3141. return !equalPath(curr.url, future.url);
  3142. case 'pathParamsOrQueryParamsChange':
  3143. return !equalPath(curr.url, future.url) ||
  3144. !shallowEqual(curr.queryParams, future.queryParams);
  3145. case 'always':
  3146. return true;
  3147. case 'paramsOrQueryParamsChange':
  3148. return !equalParamsAndUrlSegments(curr, future) ||
  3149. !shallowEqual(curr.queryParams, future.queryParams);
  3150. case 'paramsChange':
  3151. default:
  3152. return !equalParamsAndUrlSegments(curr, future);
  3153. }
  3154. }
  3155. function deactivateRouteAndItsChildren(route, context, checks) {
  3156. const children = nodeChildrenAsMap(route);
  3157. const r = route.value;
  3158. Object.entries(children).forEach(([childName, node]) => {
  3159. if (!r.component) {
  3160. deactivateRouteAndItsChildren(node, context, checks);
  3161. }
  3162. else if (context) {
  3163. deactivateRouteAndItsChildren(node, context.children.getContext(childName), checks);
  3164. }
  3165. else {
  3166. deactivateRouteAndItsChildren(node, null, checks);
  3167. }
  3168. });
  3169. if (!r.component) {
  3170. checks.canDeactivateChecks.push(new CanDeactivate(null, r));
  3171. }
  3172. else if (context && context.outlet && context.outlet.isActivated) {
  3173. checks.canDeactivateChecks.push(new CanDeactivate(context.outlet.component, r));
  3174. }
  3175. else {
  3176. checks.canDeactivateChecks.push(new CanDeactivate(null, r));
  3177. }
  3178. }
  3179. /**
  3180. * Simple function check, but generic so type inference will flow. Example:
  3181. *
  3182. * function product(a: number, b: number) {
  3183. * return a * b;
  3184. * }
  3185. *
  3186. * if (isFunction<product>(fn)) {
  3187. * return fn(1, 2);
  3188. * } else {
  3189. * throw "Must provide the `product` function";
  3190. * }
  3191. */
  3192. function isFunction(v) {
  3193. return typeof v === 'function';
  3194. }
  3195. function isBoolean(v) {
  3196. return typeof v === 'boolean';
  3197. }
  3198. function isCanLoad(guard) {
  3199. return guard && isFunction(guard.canLoad);
  3200. }
  3201. function isCanActivate(guard) {
  3202. return guard && isFunction(guard.canActivate);
  3203. }
  3204. function isCanActivateChild(guard) {
  3205. return guard && isFunction(guard.canActivateChild);
  3206. }
  3207. function isCanDeactivate(guard) {
  3208. return guard && isFunction(guard.canDeactivate);
  3209. }
  3210. function isCanMatch(guard) {
  3211. return guard && isFunction(guard.canMatch);
  3212. }
  3213. function isRedirectingNavigationCancelingError(error) {
  3214. return isNavigationCancelingError(error) && isUrlTree(error.url);
  3215. }
  3216. function isNavigationCancelingError(error) {
  3217. return error && error[NAVIGATION_CANCELING_ERROR];
  3218. }
  3219. function isEmptyError(e) {
  3220. return e instanceof EmptyError || e?.name === 'EmptyError';
  3221. }
  3222. const INITIAL_VALUE = Symbol('INITIAL_VALUE');
  3223. function prioritizedGuardValue() {
  3224. return switchMap(obs => {
  3225. return combineLatest(obs.map(o => o.pipe(take(1), startWith(INITIAL_VALUE))))
  3226. .pipe(map((results) => {
  3227. for (const result of results) {
  3228. if (result === true) {
  3229. // If result is true, check the next one
  3230. continue;
  3231. }
  3232. else if (result === INITIAL_VALUE) {
  3233. // If guard has not finished, we need to stop processing.
  3234. return INITIAL_VALUE;
  3235. }
  3236. else if (result === false || result instanceof UrlTree) {
  3237. // Result finished and was not true. Return the result.
  3238. // Note that we only allow false/UrlTree. Other values are considered invalid and
  3239. // ignored.
  3240. return result;
  3241. }
  3242. }
  3243. // Everything resolved to true. Return true.
  3244. return true;
  3245. }), filter((item) => item !== INITIAL_VALUE), take(1));
  3246. });
  3247. }
  3248. function checkGuards(injector, forwardEvent) {
  3249. return mergeMap(t => {
  3250. const { targetSnapshot, currentSnapshot, guards: { canActivateChecks, canDeactivateChecks } } = t;
  3251. if (canDeactivateChecks.length === 0 && canActivateChecks.length === 0) {
  3252. return of({ ...t, guardsResult: true });
  3253. }
  3254. return runCanDeactivateChecks(canDeactivateChecks, targetSnapshot, currentSnapshot, injector)
  3255. .pipe(mergeMap(canDeactivate => {
  3256. return canDeactivate && isBoolean(canDeactivate) ?
  3257. runCanActivateChecks(targetSnapshot, canActivateChecks, injector, forwardEvent) :
  3258. of(canDeactivate);
  3259. }), map(guardsResult => ({ ...t, guardsResult })));
  3260. });
  3261. }
  3262. function runCanDeactivateChecks(checks, futureRSS, currRSS, injector) {
  3263. return from(checks).pipe(mergeMap(check => runCanDeactivate(check.component, check.route, currRSS, futureRSS, injector)), first(result => {
  3264. return result !== true;
  3265. }, true));
  3266. }
  3267. function runCanActivateChecks(futureSnapshot, checks, injector, forwardEvent) {
  3268. return from(checks).pipe(concatMap((check) => {
  3269. return concat(fireChildActivationStart(check.route.parent, forwardEvent), fireActivationStart(check.route, forwardEvent), runCanActivateChild(futureSnapshot, check.path, injector), runCanActivate(futureSnapshot, check.route, injector));
  3270. }), first(result => {
  3271. return result !== true;
  3272. }, true));
  3273. }
  3274. /**
  3275. * This should fire off `ActivationStart` events for each route being activated at this
  3276. * level.
  3277. * In other words, if you're activating `a` and `b` below, `path` will contain the
  3278. * `ActivatedRouteSnapshot`s for both and we will fire `ActivationStart` for both. Always
  3279. * return
  3280. * `true` so checks continue to run.
  3281. */
  3282. function fireActivationStart(snapshot, forwardEvent) {
  3283. if (snapshot !== null && forwardEvent) {
  3284. forwardEvent(new ActivationStart(snapshot));
  3285. }
  3286. return of(true);
  3287. }
  3288. /**
  3289. * This should fire off `ChildActivationStart` events for each route being activated at this
  3290. * level.
  3291. * In other words, if you're activating `a` and `b` below, `path` will contain the
  3292. * `ActivatedRouteSnapshot`s for both and we will fire `ChildActivationStart` for both. Always
  3293. * return
  3294. * `true` so checks continue to run.
  3295. */
  3296. function fireChildActivationStart(snapshot, forwardEvent) {
  3297. if (snapshot !== null && forwardEvent) {
  3298. forwardEvent(new ChildActivationStart(snapshot));
  3299. }
  3300. return of(true);
  3301. }
  3302. function runCanActivate(futureRSS, futureARS, injector) {
  3303. const canActivate = futureARS.routeConfig ? futureARS.routeConfig.canActivate : null;
  3304. if (!canActivate || canActivate.length === 0)
  3305. return of(true);
  3306. const canActivateObservables = canActivate.map((canActivate) => {
  3307. return defer(() => {
  3308. const closestInjector = getClosestRouteInjector(futureARS) ?? injector;
  3309. const guard = getTokenOrFunctionIdentity(canActivate, closestInjector);
  3310. const guardVal = isCanActivate(guard) ?
  3311. guard.canActivate(futureARS, futureRSS) :
  3312. closestInjector.runInContext(() => guard(futureARS, futureRSS));
  3313. return wrapIntoObservable(guardVal).pipe(first());
  3314. });
  3315. });
  3316. return of(canActivateObservables).pipe(prioritizedGuardValue());
  3317. }
  3318. function runCanActivateChild(futureRSS, path, injector) {
  3319. const futureARS = path[path.length - 1];
  3320. const canActivateChildGuards = path.slice(0, path.length - 1)
  3321. .reverse()
  3322. .map(p => getCanActivateChild(p))
  3323. .filter(_ => _ !== null);
  3324. const canActivateChildGuardsMapped = canActivateChildGuards.map((d) => {
  3325. return defer(() => {
  3326. const guardsMapped = d.guards.map((canActivateChild) => {
  3327. const closestInjector = getClosestRouteInjector(d.node) ?? injector;
  3328. const guard = getTokenOrFunctionIdentity(canActivateChild, closestInjector);
  3329. const guardVal = isCanActivateChild(guard) ?
  3330. guard.canActivateChild(futureARS, futureRSS) :
  3331. closestInjector.runInContext(() => guard(futureARS, futureRSS));
  3332. return wrapIntoObservable(guardVal).pipe(first());
  3333. });
  3334. return of(guardsMapped).pipe(prioritizedGuardValue());
  3335. });
  3336. });
  3337. return of(canActivateChildGuardsMapped).pipe(prioritizedGuardValue());
  3338. }
  3339. function runCanDeactivate(component, currARS, currRSS, futureRSS, injector) {
  3340. const canDeactivate = currARS && currARS.routeConfig ? currARS.routeConfig.canDeactivate : null;
  3341. if (!canDeactivate || canDeactivate.length === 0)
  3342. return of(true);
  3343. const canDeactivateObservables = canDeactivate.map((c) => {
  3344. const closestInjector = getClosestRouteInjector(currARS) ?? injector;
  3345. const guard = getTokenOrFunctionIdentity(c, closestInjector);
  3346. const guardVal = isCanDeactivate(guard) ?
  3347. guard.canDeactivate(component, currARS, currRSS, futureRSS) :
  3348. closestInjector.runInContext(() => guard(component, currARS, currRSS, futureRSS));
  3349. return wrapIntoObservable(guardVal).pipe(first());
  3350. });
  3351. return of(canDeactivateObservables).pipe(prioritizedGuardValue());
  3352. }
  3353. function runCanLoadGuards(injector, route, segments, urlSerializer) {
  3354. const canLoad = route.canLoad;
  3355. if (canLoad === undefined || canLoad.length === 0) {
  3356. return of(true);
  3357. }
  3358. const canLoadObservables = canLoad.map((injectionToken) => {
  3359. const guard = getTokenOrFunctionIdentity(injectionToken, injector);
  3360. const guardVal = isCanLoad(guard) ?
  3361. guard.canLoad(route, segments) :
  3362. injector.runInContext(() => guard(route, segments));
  3363. return wrapIntoObservable(guardVal);
  3364. });
  3365. return of(canLoadObservables)
  3366. .pipe(prioritizedGuardValue(), redirectIfUrlTree(urlSerializer));
  3367. }
  3368. function redirectIfUrlTree(urlSerializer) {
  3369. return pipe(tap((result) => {
  3370. if (!isUrlTree(result))
  3371. return;
  3372. throw redirectingNavigationError(urlSerializer, result);
  3373. }), map(result => result === true));
  3374. }
  3375. function runCanMatchGuards(injector, route, segments, urlSerializer) {
  3376. const canMatch = route.canMatch;
  3377. if (!canMatch || canMatch.length === 0)
  3378. return of(true);
  3379. const canMatchObservables = canMatch.map(injectionToken => {
  3380. const guard = getTokenOrFunctionIdentity(injectionToken, injector);
  3381. const guardVal = isCanMatch(guard) ?
  3382. guard.canMatch(route, segments) :
  3383. injector.runInContext(() => guard(route, segments));
  3384. return wrapIntoObservable(guardVal);
  3385. });
  3386. return of(canMatchObservables)
  3387. .pipe(prioritizedGuardValue(), redirectIfUrlTree(urlSerializer));
  3388. }
  3389. class NoMatch {
  3390. constructor(segmentGroup) {
  3391. this.segmentGroup = segmentGroup || null;
  3392. }
  3393. }
  3394. class AbsoluteRedirect {
  3395. constructor(urlTree) {
  3396. this.urlTree = urlTree;
  3397. }
  3398. }
  3399. function noMatch$1(segmentGroup) {
  3400. return throwError(new NoMatch(segmentGroup));
  3401. }
  3402. function absoluteRedirect(newTree) {
  3403. return throwError(new AbsoluteRedirect(newTree));
  3404. }
  3405. function namedOutletsRedirect(redirectTo) {
  3406. return throwError(new ɵRuntimeError(4000 /* RuntimeErrorCode.NAMED_OUTLET_REDIRECT */, (typeof ngDevMode === 'undefined' || ngDevMode) &&
  3407. `Only absolute redirects can have named outlets. redirectTo: '${redirectTo}'`));
  3408. }
  3409. function canLoadFails(route) {
  3410. return throwError(navigationCancelingError((typeof ngDevMode === 'undefined' || ngDevMode) &&
  3411. `Cannot load children because the guard of the route "path: '${route.path}'" returned false`, 3 /* NavigationCancellationCode.GuardRejected */));
  3412. }
  3413. class ApplyRedirects {
  3414. constructor(urlSerializer, urlTree) {
  3415. this.urlSerializer = urlSerializer;
  3416. this.urlTree = urlTree;
  3417. }
  3418. noMatchError(e) {
  3419. return new ɵRuntimeError(4002 /* RuntimeErrorCode.NO_MATCH */, (typeof ngDevMode === 'undefined' || ngDevMode) &&
  3420. `Cannot match any routes. URL Segment: '${e.segmentGroup}'`);
  3421. }
  3422. lineralizeSegments(route, urlTree) {
  3423. let res = [];
  3424. let c = urlTree.root;
  3425. while (true) {
  3426. res = res.concat(c.segments);
  3427. if (c.numberOfChildren === 0) {
  3428. return of(res);
  3429. }
  3430. if (c.numberOfChildren > 1 || !c.children[PRIMARY_OUTLET]) {
  3431. return namedOutletsRedirect(route.redirectTo);
  3432. }
  3433. c = c.children[PRIMARY_OUTLET];
  3434. }
  3435. }
  3436. applyRedirectCommands(segments, redirectTo, posParams) {
  3437. return this.applyRedirectCreateUrlTree(redirectTo, this.urlSerializer.parse(redirectTo), segments, posParams);
  3438. }
  3439. applyRedirectCreateUrlTree(redirectTo, urlTree, segments, posParams) {
  3440. const newRoot = this.createSegmentGroup(redirectTo, urlTree.root, segments, posParams);
  3441. return new UrlTree(newRoot, this.createQueryParams(urlTree.queryParams, this.urlTree.queryParams), urlTree.fragment);
  3442. }
  3443. createQueryParams(redirectToParams, actualParams) {
  3444. const res = {};
  3445. Object.entries(redirectToParams).forEach(([k, v]) => {
  3446. const copySourceValue = typeof v === 'string' && v.startsWith(':');
  3447. if (copySourceValue) {
  3448. const sourceName = v.substring(1);
  3449. res[k] = actualParams[sourceName];
  3450. }
  3451. else {
  3452. res[k] = v;
  3453. }
  3454. });
  3455. return res;
  3456. }
  3457. createSegmentGroup(redirectTo, group, segments, posParams) {
  3458. const updatedSegments = this.createSegments(redirectTo, group.segments, segments, posParams);
  3459. let children = {};
  3460. Object.entries(group.children).forEach(([name, child]) => {
  3461. children[name] = this.createSegmentGroup(redirectTo, child, segments, posParams);
  3462. });
  3463. return new UrlSegmentGroup(updatedSegments, children);
  3464. }
  3465. createSegments(redirectTo, redirectToSegments, actualSegments, posParams) {
  3466. return redirectToSegments.map(s => s.path.startsWith(':') ? this.findPosParam(redirectTo, s, posParams) :
  3467. this.findOrReturn(s, actualSegments));
  3468. }
  3469. findPosParam(redirectTo, redirectToUrlSegment, posParams) {
  3470. const pos = posParams[redirectToUrlSegment.path.substring(1)];
  3471. if (!pos)
  3472. throw new ɵRuntimeError(4001 /* RuntimeErrorCode.MISSING_REDIRECT */, (typeof ngDevMode === 'undefined' || ngDevMode) &&
  3473. `Cannot redirect to '${redirectTo}'. Cannot find '${redirectToUrlSegment.path}'.`);
  3474. return pos;
  3475. }
  3476. findOrReturn(redirectToUrlSegment, actualSegments) {
  3477. let idx = 0;
  3478. for (const s of actualSegments) {
  3479. if (s.path === redirectToUrlSegment.path) {
  3480. actualSegments.splice(idx);
  3481. return s;
  3482. }
  3483. idx++;
  3484. }
  3485. return redirectToUrlSegment;
  3486. }
  3487. }
  3488. const noMatch = {
  3489. matched: false,
  3490. consumedSegments: [],
  3491. remainingSegments: [],
  3492. parameters: {},
  3493. positionalParamSegments: {}
  3494. };
  3495. function matchWithChecks(segmentGroup, route, segments, injector, urlSerializer) {
  3496. const result = match(segmentGroup, route, segments);
  3497. if (!result.matched) {
  3498. return of(result);
  3499. }
  3500. // Only create the Route's `EnvironmentInjector` if it matches the attempted
  3501. // navigation
  3502. injector = getOrCreateRouteInjectorIfNeeded(route, injector);
  3503. return runCanMatchGuards(injector, route, segments, urlSerializer)
  3504. .pipe(map((v) => v === true ? result : { ...noMatch }));
  3505. }
  3506. function match(segmentGroup, route, segments) {
  3507. if (route.path === '') {
  3508. if (route.pathMatch === 'full' && (segmentGroup.hasChildren() || segments.length > 0)) {
  3509. return { ...noMatch };
  3510. }
  3511. return {
  3512. matched: true,
  3513. consumedSegments: [],
  3514. remainingSegments: segments,
  3515. parameters: {},
  3516. positionalParamSegments: {}
  3517. };
  3518. }
  3519. const matcher = route.matcher || defaultUrlMatcher;
  3520. const res = matcher(segments, segmentGroup, route);
  3521. if (!res)
  3522. return { ...noMatch };
  3523. const posParams = {};
  3524. Object.entries(res.posParams ?? {}).forEach(([k, v]) => {
  3525. posParams[k] = v.path;
  3526. });
  3527. const parameters = res.consumed.length > 0 ?
  3528. { ...posParams, ...res.consumed[res.consumed.length - 1].parameters } :
  3529. posParams;
  3530. return {
  3531. matched: true,
  3532. consumedSegments: res.consumed,
  3533. remainingSegments: segments.slice(res.consumed.length),
  3534. // TODO(atscott): investigate combining parameters and positionalParamSegments
  3535. parameters,
  3536. positionalParamSegments: res.posParams ?? {}
  3537. };
  3538. }
  3539. function split(segmentGroup, consumedSegments, slicedSegments, config) {
  3540. if (slicedSegments.length > 0 &&
  3541. containsEmptyPathMatchesWithNamedOutlets(segmentGroup, slicedSegments, config)) {
  3542. const s = new UrlSegmentGroup(consumedSegments, createChildrenForEmptyPaths(config, new UrlSegmentGroup(slicedSegments, segmentGroup.children)));
  3543. return { segmentGroup: s, slicedSegments: [] };
  3544. }
  3545. if (slicedSegments.length === 0 &&
  3546. containsEmptyPathMatches(segmentGroup, slicedSegments, config)) {
  3547. const s = new UrlSegmentGroup(segmentGroup.segments, addEmptyPathsToChildrenIfNeeded(segmentGroup, consumedSegments, slicedSegments, config, segmentGroup.children));
  3548. return { segmentGroup: s, slicedSegments };
  3549. }
  3550. const s = new UrlSegmentGroup(segmentGroup.segments, segmentGroup.children);
  3551. return { segmentGroup: s, slicedSegments };
  3552. }
  3553. function addEmptyPathsToChildrenIfNeeded(segmentGroup, consumedSegments, slicedSegments, routes, children) {
  3554. const res = {};
  3555. for (const r of routes) {
  3556. if (emptyPathMatch(segmentGroup, slicedSegments, r) && !children[getOutlet(r)]) {
  3557. const s = new UrlSegmentGroup([], {});
  3558. res[getOutlet(r)] = s;
  3559. }
  3560. }
  3561. return { ...children, ...res };
  3562. }
  3563. function createChildrenForEmptyPaths(routes, primarySegment) {
  3564. const res = {};
  3565. res[PRIMARY_OUTLET] = primarySegment;
  3566. for (const r of routes) {
  3567. if (r.path === '' && getOutlet(r) !== PRIMARY_OUTLET) {
  3568. const s = new UrlSegmentGroup([], {});
  3569. res[getOutlet(r)] = s;
  3570. }
  3571. }
  3572. return res;
  3573. }
  3574. function containsEmptyPathMatchesWithNamedOutlets(segmentGroup, slicedSegments, routes) {
  3575. return routes.some(r => emptyPathMatch(segmentGroup, slicedSegments, r) && getOutlet(r) !== PRIMARY_OUTLET);
  3576. }
  3577. function containsEmptyPathMatches(segmentGroup, slicedSegments, routes) {
  3578. return routes.some(r => emptyPathMatch(segmentGroup, slicedSegments, r));
  3579. }
  3580. function emptyPathMatch(segmentGroup, slicedSegments, r) {
  3581. if ((segmentGroup.hasChildren() || slicedSegments.length > 0) && r.pathMatch === 'full') {
  3582. return false;
  3583. }
  3584. return r.path === '';
  3585. }
  3586. /**
  3587. * Determines if `route` is a path match for the `rawSegment`, `segments`, and `outlet` without
  3588. * verifying that its children are a full match for the remainder of the `rawSegment` children as
  3589. * well.
  3590. */
  3591. function isImmediateMatch(route, rawSegment, segments, outlet) {
  3592. // We allow matches to empty paths when the outlets differ so we can match a url like `/(b:b)` to
  3593. // a config like
  3594. // * `{path: '', children: [{path: 'b', outlet: 'b'}]}`
  3595. // or even
  3596. // * `{path: '', outlet: 'a', children: [{path: 'b', outlet: 'b'}]`
  3597. //
  3598. // The exception here is when the segment outlet is for the primary outlet. This would
  3599. // result in a match inside the named outlet because all children there are written as primary
  3600. // outlets. So we need to prevent child named outlet matches in a url like `/b` in a config like
  3601. // * `{path: '', outlet: 'x' children: [{path: 'b'}]}`
  3602. // This should only match if the url is `/(x:b)`.
  3603. if (getOutlet(route) !== outlet &&
  3604. (outlet === PRIMARY_OUTLET || !emptyPathMatch(rawSegment, segments, route))) {
  3605. return false;
  3606. }
  3607. if (route.path === '**') {
  3608. return true;
  3609. }
  3610. return match(rawSegment, route, segments).matched;
  3611. }
  3612. function noLeftoversInUrl(segmentGroup, segments, outlet) {
  3613. return segments.length === 0 && !segmentGroup.children[outlet];
  3614. }
  3615. function recognize$1(injector, configLoader, rootComponentType, config, urlTree, urlSerializer, paramsInheritanceStrategy = 'emptyOnly') {
  3616. return new Recognizer(injector, configLoader, rootComponentType, config, urlTree, paramsInheritanceStrategy, urlSerializer)
  3617. .recognize();
  3618. }
  3619. class Recognizer {
  3620. constructor(injector, configLoader, rootComponentType, config, urlTree, paramsInheritanceStrategy, urlSerializer) {
  3621. this.injector = injector;
  3622. this.configLoader = configLoader;
  3623. this.rootComponentType = rootComponentType;
  3624. this.config = config;
  3625. this.urlTree = urlTree;
  3626. this.paramsInheritanceStrategy = paramsInheritanceStrategy;
  3627. this.urlSerializer = urlSerializer;
  3628. this.allowRedirects = true;
  3629. this.applyRedirects = new ApplyRedirects(this.urlSerializer, this.urlTree);
  3630. }
  3631. noMatchError(e) {
  3632. return new ɵRuntimeError(4002 /* RuntimeErrorCode.NO_MATCH */, (typeof ngDevMode === 'undefined' || ngDevMode) &&
  3633. `Cannot match any routes. URL Segment: '${e.segmentGroup}'`);
  3634. }
  3635. recognize() {
  3636. const rootSegmentGroup = split(this.urlTree.root, [], [], this.config).segmentGroup;
  3637. return this.processSegmentGroup(this.injector, this.config, rootSegmentGroup, PRIMARY_OUTLET)
  3638. .pipe(catchError((e) => {
  3639. if (e instanceof AbsoluteRedirect) {
  3640. // After an absolute redirect we do not apply any more redirects!
  3641. // If this implementation changes, update the documentation note in `redirectTo`.
  3642. this.allowRedirects = false;
  3643. this.urlTree = e.urlTree;
  3644. return this.match(e.urlTree);
  3645. }
  3646. if (e instanceof NoMatch) {
  3647. throw this.noMatchError(e);
  3648. }
  3649. throw e;
  3650. }), map(children => {
  3651. // Use Object.freeze to prevent readers of the Router state from modifying it outside
  3652. // of a navigation, resulting in the router being out of sync with the browser.
  3653. const root = new ActivatedRouteSnapshot([], Object.freeze({}), Object.freeze({ ...this.urlTree.queryParams }), this.urlTree.fragment, {}, PRIMARY_OUTLET, this.rootComponentType, null, {});
  3654. const rootNode = new TreeNode(root, children);
  3655. const routeState = new RouterStateSnapshot('', rootNode);
  3656. const tree = createUrlTreeFromSnapshot(root, [], this.urlTree.queryParams, this.urlTree.fragment);
  3657. // https://github.com/angular/angular/issues/47307
  3658. // Creating the tree stringifies the query params
  3659. // We don't want to do this here so reassign them to the original.
  3660. tree.queryParams = this.urlTree.queryParams;
  3661. routeState.url = this.urlSerializer.serialize(tree);
  3662. this.inheritParamsAndData(routeState._root);
  3663. return { state: routeState, tree };
  3664. }));
  3665. }
  3666. match(tree) {
  3667. const expanded$ = this.processSegmentGroup(this.injector, this.config, tree.root, PRIMARY_OUTLET);
  3668. return expanded$.pipe(catchError((e) => {
  3669. if (e instanceof NoMatch) {
  3670. throw this.noMatchError(e);
  3671. }
  3672. throw e;
  3673. }));
  3674. }
  3675. inheritParamsAndData(routeNode) {
  3676. const route = routeNode.value;
  3677. const i = inheritedParamsDataResolve(route, this.paramsInheritanceStrategy);
  3678. route.params = Object.freeze(i.params);
  3679. route.data = Object.freeze(i.data);
  3680. routeNode.children.forEach(n => this.inheritParamsAndData(n));
  3681. }
  3682. processSegmentGroup(injector, config, segmentGroup, outlet) {
  3683. if (segmentGroup.segments.length === 0 && segmentGroup.hasChildren()) {
  3684. return this.processChildren(injector, config, segmentGroup);
  3685. }
  3686. return this.processSegment(injector, config, segmentGroup, segmentGroup.segments, outlet, true);
  3687. }
  3688. /**
  3689. * Matches every child outlet in the `segmentGroup` to a `Route` in the config. Returns `null` if
  3690. * we cannot find a match for _any_ of the children.
  3691. *
  3692. * @param config - The `Routes` to match against
  3693. * @param segmentGroup - The `UrlSegmentGroup` whose children need to be matched against the
  3694. * config.
  3695. */
  3696. processChildren(injector, config, segmentGroup) {
  3697. // Expand outlets one at a time, starting with the primary outlet. We need to do it this way
  3698. // because an absolute redirect from the primary outlet takes precedence.
  3699. const childOutlets = [];
  3700. for (const child of Object.keys(segmentGroup.children)) {
  3701. if (child === 'primary') {
  3702. childOutlets.unshift(child);
  3703. }
  3704. else {
  3705. childOutlets.push(child);
  3706. }
  3707. }
  3708. return from(childOutlets)
  3709. .pipe(concatMap(childOutlet => {
  3710. const child = segmentGroup.children[childOutlet];
  3711. // Sort the config so that routes with outlets that match the one being activated
  3712. // appear first, followed by routes for other outlets, which might match if they have
  3713. // an empty path.
  3714. const sortedConfig = sortByMatchingOutlets(config, childOutlet);
  3715. return this.processSegmentGroup(injector, sortedConfig, child, childOutlet);
  3716. }), scan((children, outletChildren) => {
  3717. children.push(...outletChildren);
  3718. return children;
  3719. }), defaultIfEmpty(null), last$1(), mergeMap(children => {
  3720. if (children === null)
  3721. return noMatch$1(segmentGroup);
  3722. // Because we may have matched two outlets to the same empty path segment, we can have
  3723. // multiple activated results for the same outlet. We should merge the children of
  3724. // these results so the final return value is only one `TreeNode` per outlet.
  3725. const mergedChildren = mergeEmptyPathMatches(children);
  3726. if (typeof ngDevMode === 'undefined' || ngDevMode) {
  3727. // This should really never happen - we are only taking the first match for each
  3728. // outlet and merge the empty path matches.
  3729. checkOutletNameUniqueness(mergedChildren);
  3730. }
  3731. sortActivatedRouteSnapshots(mergedChildren);
  3732. return of(mergedChildren);
  3733. }));
  3734. }
  3735. processSegment(injector, routes, segmentGroup, segments, outlet, allowRedirects) {
  3736. return from(routes).pipe(concatMap(r => {
  3737. return this
  3738. .processSegmentAgainstRoute(r._injector ?? injector, routes, r, segmentGroup, segments, outlet, allowRedirects)
  3739. .pipe(catchError((e) => {
  3740. if (e instanceof NoMatch) {
  3741. return of(null);
  3742. }
  3743. throw e;
  3744. }));
  3745. }), first((x) => !!x), catchError(e => {
  3746. if (isEmptyError(e)) {
  3747. if (noLeftoversInUrl(segmentGroup, segments, outlet)) {
  3748. return of([]);
  3749. }
  3750. return noMatch$1(segmentGroup);
  3751. }
  3752. throw e;
  3753. }));
  3754. }
  3755. processSegmentAgainstRoute(injector, routes, route, rawSegment, segments, outlet, allowRedirects) {
  3756. if (!isImmediateMatch(route, rawSegment, segments, outlet))
  3757. return noMatch$1(rawSegment);
  3758. if (route.redirectTo === undefined) {
  3759. return this.matchSegmentAgainstRoute(injector, rawSegment, route, segments, outlet, allowRedirects);
  3760. }
  3761. if (allowRedirects && this.allowRedirects) {
  3762. return this.expandSegmentAgainstRouteUsingRedirect(injector, rawSegment, routes, route, segments, outlet);
  3763. }
  3764. return noMatch$1(rawSegment);
  3765. }
  3766. expandSegmentAgainstRouteUsingRedirect(injector, segmentGroup, routes, route, segments, outlet) {
  3767. if (route.path === '**') {
  3768. return this.expandWildCardWithParamsAgainstRouteUsingRedirect(injector, routes, route, outlet);
  3769. }
  3770. return this.expandRegularSegmentAgainstRouteUsingRedirect(injector, segmentGroup, routes, route, segments, outlet);
  3771. }
  3772. expandWildCardWithParamsAgainstRouteUsingRedirect(injector, routes, route, outlet) {
  3773. const newTree = this.applyRedirects.applyRedirectCommands([], route.redirectTo, {});
  3774. if (route.redirectTo.startsWith('/')) {
  3775. return absoluteRedirect(newTree);
  3776. }
  3777. return this.applyRedirects.lineralizeSegments(route, newTree)
  3778. .pipe(mergeMap((newSegments) => {
  3779. const group = new UrlSegmentGroup(newSegments, {});
  3780. return this.processSegment(injector, routes, group, newSegments, outlet, false);
  3781. }));
  3782. }
  3783. expandRegularSegmentAgainstRouteUsingRedirect(injector, segmentGroup, routes, route, segments, outlet) {
  3784. const { matched, consumedSegments, remainingSegments, positionalParamSegments } = match(segmentGroup, route, segments);
  3785. if (!matched)
  3786. return noMatch$1(segmentGroup);
  3787. const newTree = this.applyRedirects.applyRedirectCommands(consumedSegments, route.redirectTo, positionalParamSegments);
  3788. if (route.redirectTo.startsWith('/')) {
  3789. return absoluteRedirect(newTree);
  3790. }
  3791. return this.applyRedirects.lineralizeSegments(route, newTree)
  3792. .pipe(mergeMap((newSegments) => {
  3793. return this.processSegment(injector, routes, segmentGroup, newSegments.concat(remainingSegments), outlet, false);
  3794. }));
  3795. }
  3796. matchSegmentAgainstRoute(injector, rawSegment, route, segments, outlet, allowRedirects) {
  3797. let matchResult;
  3798. if (route.path === '**') {
  3799. const params = segments.length > 0 ? last(segments).parameters : {};
  3800. const snapshot = new ActivatedRouteSnapshot(segments, params, Object.freeze({ ...this.urlTree.queryParams }), this.urlTree.fragment, getData(route), getOutlet(route), route.component ?? route._loadedComponent ?? null, route, getResolve(route));
  3801. matchResult = of({
  3802. snapshot,
  3803. consumedSegments: [],
  3804. remainingSegments: [],
  3805. });
  3806. // Prior versions of the route matching algorithm would stop matching at the wildcard route.
  3807. // We should investigate a better strategy for any existing children. Otherwise, these
  3808. // child segments are silently dropped from the navigation.
  3809. // https://github.com/angular/angular/issues/40089
  3810. rawSegment.children = {};
  3811. }
  3812. else {
  3813. matchResult =
  3814. matchWithChecks(rawSegment, route, segments, injector, this.urlSerializer)
  3815. .pipe(map(({ matched, consumedSegments, remainingSegments, parameters }) => {
  3816. if (!matched) {
  3817. return null;
  3818. }
  3819. const snapshot = new ActivatedRouteSnapshot(consumedSegments, parameters, Object.freeze({ ...this.urlTree.queryParams }), this.urlTree.fragment, getData(route), getOutlet(route), route.component ?? route._loadedComponent ?? null, route, getResolve(route));
  3820. return { snapshot, consumedSegments, remainingSegments };
  3821. }));
  3822. }
  3823. return matchResult.pipe(switchMap((result) => {
  3824. if (result === null) {
  3825. return noMatch$1(rawSegment);
  3826. }
  3827. // If the route has an injector created from providers, we should start using that.
  3828. injector = route._injector ?? injector;
  3829. return this.getChildConfig(injector, route, segments)
  3830. .pipe(switchMap(({ routes: childConfig }) => {
  3831. const childInjector = route._loadedInjector ?? injector;
  3832. const { snapshot, consumedSegments, remainingSegments } = result;
  3833. const { segmentGroup, slicedSegments } = split(rawSegment, consumedSegments, remainingSegments, childConfig);
  3834. if (slicedSegments.length === 0 && segmentGroup.hasChildren()) {
  3835. return this.processChildren(childInjector, childConfig, segmentGroup)
  3836. .pipe(map(children => {
  3837. if (children === null) {
  3838. return null;
  3839. }
  3840. return [new TreeNode(snapshot, children)];
  3841. }));
  3842. }
  3843. if (childConfig.length === 0 && slicedSegments.length === 0) {
  3844. return of([new TreeNode(snapshot, [])]);
  3845. }
  3846. const matchedOnOutlet = getOutlet(route) === outlet;
  3847. // If we matched a config due to empty path match on a different outlet, we need to
  3848. // continue passing the current outlet for the segment rather than switch to PRIMARY.
  3849. // Note that we switch to primary when we have a match because outlet configs look like
  3850. // this: {path: 'a', outlet: 'a', children: [
  3851. // {path: 'b', component: B},
  3852. // {path: 'c', component: C},
  3853. // ]}
  3854. // Notice that the children of the named outlet are configured with the primary outlet
  3855. return this
  3856. .processSegment(childInjector, childConfig, segmentGroup, slicedSegments, matchedOnOutlet ? PRIMARY_OUTLET : outlet, true)
  3857. .pipe(map(children => {
  3858. return [new TreeNode(snapshot, children)];
  3859. }));
  3860. }));
  3861. }));
  3862. }
  3863. getChildConfig(injector, route, segments) {
  3864. if (route.children) {
  3865. // The children belong to the same module
  3866. return of({ routes: route.children, injector });
  3867. }
  3868. if (route.loadChildren) {
  3869. // lazy children belong to the loaded module
  3870. if (route._loadedRoutes !== undefined) {
  3871. return of({ routes: route._loadedRoutes, injector: route._loadedInjector });
  3872. }
  3873. return runCanLoadGuards(injector, route, segments, this.urlSerializer)
  3874. .pipe(mergeMap((shouldLoadResult) => {
  3875. if (shouldLoadResult) {
  3876. return this.configLoader.loadChildren(injector, route)
  3877. .pipe(tap((cfg) => {
  3878. route._loadedRoutes = cfg.routes;
  3879. route._loadedInjector = cfg.injector;
  3880. }));
  3881. }
  3882. return canLoadFails(route);
  3883. }));
  3884. }
  3885. return of({ routes: [], injector });
  3886. }
  3887. }
  3888. function sortActivatedRouteSnapshots(nodes) {
  3889. nodes.sort((a, b) => {
  3890. if (a.value.outlet === PRIMARY_OUTLET)
  3891. return -1;
  3892. if (b.value.outlet === PRIMARY_OUTLET)
  3893. return 1;
  3894. return a.value.outlet.localeCompare(b.value.outlet);
  3895. });
  3896. }
  3897. function hasEmptyPathConfig(node) {
  3898. const config = node.value.routeConfig;
  3899. return config && config.path === '';
  3900. }
  3901. /**
  3902. * Finds `TreeNode`s with matching empty path route configs and merges them into `TreeNode` with
  3903. * the children from each duplicate. This is necessary because different outlets can match a
  3904. * single empty path route config and the results need to then be merged.
  3905. */
  3906. function mergeEmptyPathMatches(nodes) {
  3907. const result = [];
  3908. // The set of nodes which contain children that were merged from two duplicate empty path nodes.
  3909. const mergedNodes = new Set();
  3910. for (const node of nodes) {
  3911. if (!hasEmptyPathConfig(node)) {
  3912. result.push(node);
  3913. continue;
  3914. }
  3915. const duplicateEmptyPathNode = result.find(resultNode => node.value.routeConfig === resultNode.value.routeConfig);
  3916. if (duplicateEmptyPathNode !== undefined) {
  3917. duplicateEmptyPathNode.children.push(...node.children);
  3918. mergedNodes.add(duplicateEmptyPathNode);
  3919. }
  3920. else {
  3921. result.push(node);
  3922. }
  3923. }
  3924. // For each node which has children from multiple sources, we need to recompute a new `TreeNode`
  3925. // by also merging those children. This is necessary when there are multiple empty path configs
  3926. // in a row. Put another way: whenever we combine children of two nodes, we need to also check
  3927. // if any of those children can be combined into a single node as well.
  3928. for (const mergedNode of mergedNodes) {
  3929. const mergedChildren = mergeEmptyPathMatches(mergedNode.children);
  3930. result.push(new TreeNode(mergedNode.value, mergedChildren));
  3931. }
  3932. return result.filter(n => !mergedNodes.has(n));
  3933. }
  3934. function checkOutletNameUniqueness(nodes) {
  3935. const names = {};
  3936. nodes.forEach(n => {
  3937. const routeWithSameOutletName = names[n.value.outlet];
  3938. if (routeWithSameOutletName) {
  3939. const p = routeWithSameOutletName.url.map(s => s.toString()).join('/');
  3940. const c = n.value.url.map(s => s.toString()).join('/');
  3941. throw new ɵRuntimeError(4006 /* RuntimeErrorCode.TWO_SEGMENTS_WITH_SAME_OUTLET */, (typeof ngDevMode === 'undefined' || ngDevMode) &&
  3942. `Two segments cannot have the same outlet name: '${p}' and '${c}'.`);
  3943. }
  3944. names[n.value.outlet] = n.value;
  3945. });
  3946. }
  3947. function getData(route) {
  3948. return route.data || {};
  3949. }
  3950. function getResolve(route) {
  3951. return route.resolve || {};
  3952. }
  3953. function recognize(injector, configLoader, rootComponentType, config, serializer, paramsInheritanceStrategy) {
  3954. return mergeMap(t => recognize$1(injector, configLoader, rootComponentType, config, t.extractedUrl, serializer, paramsInheritanceStrategy)
  3955. .pipe(map(({ state: targetSnapshot, tree: urlAfterRedirects }) => {
  3956. return { ...t, targetSnapshot, urlAfterRedirects };
  3957. })));
  3958. }
  3959. function resolveData(paramsInheritanceStrategy, injector) {
  3960. return mergeMap(t => {
  3961. const { targetSnapshot, guards: { canActivateChecks } } = t;
  3962. if (!canActivateChecks.length) {
  3963. return of(t);
  3964. }
  3965. let canActivateChecksResolved = 0;
  3966. return from(canActivateChecks)
  3967. .pipe(concatMap(check => runResolve(check.route, targetSnapshot, paramsInheritanceStrategy, injector)), tap(() => canActivateChecksResolved++), takeLast(1), mergeMap(_ => canActivateChecksResolved === canActivateChecks.length ? of(t) : EMPTY));
  3968. });
  3969. }
  3970. function runResolve(futureARS, futureRSS, paramsInheritanceStrategy, injector) {
  3971. const config = futureARS.routeConfig;
  3972. const resolve = futureARS._resolve;
  3973. if (config?.title !== undefined && !hasStaticTitle(config)) {
  3974. resolve[RouteTitleKey] = config.title;
  3975. }
  3976. return resolveNode(resolve, futureARS, futureRSS, injector).pipe(map((resolvedData) => {
  3977. futureARS._resolvedData = resolvedData;
  3978. futureARS.data = inheritedParamsDataResolve(futureARS, paramsInheritanceStrategy).resolve;
  3979. if (config && hasStaticTitle(config)) {
  3980. futureARS.data[RouteTitleKey] = config.title;
  3981. }
  3982. return null;
  3983. }));
  3984. }
  3985. function resolveNode(resolve, futureARS, futureRSS, injector) {
  3986. const keys = getDataKeys(resolve);
  3987. if (keys.length === 0) {
  3988. return of({});
  3989. }
  3990. const data = {};
  3991. return from(keys).pipe(mergeMap(key => getResolver(resolve[key], futureARS, futureRSS, injector)
  3992. .pipe(first(), tap((value) => {
  3993. data[key] = value;
  3994. }))), takeLast(1), mapTo(data), catchError((e) => isEmptyError(e) ? EMPTY : throwError(e)));
  3995. }
  3996. function getDataKeys(obj) {
  3997. return [...Object.keys(obj), ...Object.getOwnPropertySymbols(obj)];
  3998. }
  3999. function getResolver(injectionToken, futureARS, futureRSS, injector) {
  4000. const closestInjector = getClosestRouteInjector(futureARS) ?? injector;
  4001. const resolver = getTokenOrFunctionIdentity(injectionToken, closestInjector);
  4002. const resolverValue = resolver.resolve ?
  4003. resolver.resolve(futureARS, futureRSS) :
  4004. closestInjector.runInContext(() => resolver(futureARS, futureRSS));
  4005. return wrapIntoObservable(resolverValue);
  4006. }
  4007. function hasStaticTitle(config) {
  4008. return typeof config.title === 'string' || config.title === null;
  4009. }
  4010. /**
  4011. * Perform a side effect through a switchMap for every emission on the source Observable,
  4012. * but return an Observable that is identical to the source. It's essentially the same as
  4013. * the `tap` operator, but if the side effectful `next` function returns an ObservableInput,
  4014. * it will wait before continuing with the original value.
  4015. */
  4016. function switchTap(next) {
  4017. return switchMap(v => {
  4018. const nextResult = next(v);
  4019. if (nextResult) {
  4020. return from(nextResult).pipe(map(() => v));
  4021. }
  4022. return of(v);
  4023. });
  4024. }
  4025. /**
  4026. * The [DI token](guide/glossary/#di-token) for a router configuration.
  4027. *
  4028. * `ROUTES` is a low level API for router configuration via dependency injection.
  4029. *
  4030. * We recommend that in almost all cases to use higher level APIs such as `RouterModule.forRoot()`,
  4031. * `provideRouter`, or `Router.resetConfig()`.
  4032. *
  4033. * @publicApi
  4034. */
  4035. const ROUTES = new InjectionToken('ROUTES');
  4036. class RouterConfigLoader {
  4037. constructor() {
  4038. this.componentLoaders = new WeakMap();
  4039. this.childrenLoaders = new WeakMap();
  4040. this.compiler = inject(Compiler);
  4041. }
  4042. loadComponent(route) {
  4043. if (this.componentLoaders.get(route)) {
  4044. return this.componentLoaders.get(route);
  4045. }
  4046. else if (route._loadedComponent) {
  4047. return of(route._loadedComponent);
  4048. }
  4049. if (this.onLoadStartListener) {
  4050. this.onLoadStartListener(route);
  4051. }
  4052. const loadRunner = wrapIntoObservable(route.loadComponent())
  4053. .pipe(map(maybeUnwrapDefaultExport), tap(component => {
  4054. if (this.onLoadEndListener) {
  4055. this.onLoadEndListener(route);
  4056. }
  4057. (typeof ngDevMode === 'undefined' || ngDevMode) &&
  4058. assertStandalone(route.path ?? '', component);
  4059. route._loadedComponent = component;
  4060. }), finalize(() => {
  4061. this.componentLoaders.delete(route);
  4062. }));
  4063. // Use custom ConnectableObservable as share in runners pipe increasing the bundle size too much
  4064. const loader = new ConnectableObservable(loadRunner, () => new Subject()).pipe(refCount());
  4065. this.componentLoaders.set(route, loader);
  4066. return loader;
  4067. }
  4068. loadChildren(parentInjector, route) {
  4069. if (this.childrenLoaders.get(route)) {
  4070. return this.childrenLoaders.get(route);
  4071. }
  4072. else if (route._loadedRoutes) {
  4073. return of({ routes: route._loadedRoutes, injector: route._loadedInjector });
  4074. }
  4075. if (this.onLoadStartListener) {
  4076. this.onLoadStartListener(route);
  4077. }
  4078. const moduleFactoryOrRoutes$ = this.loadModuleFactoryOrRoutes(route.loadChildren);
  4079. const loadRunner = moduleFactoryOrRoutes$.pipe(map((factoryOrRoutes) => {
  4080. if (this.onLoadEndListener) {
  4081. this.onLoadEndListener(route);
  4082. }
  4083. // This injector comes from the `NgModuleRef` when lazy loading an `NgModule`. There is no
  4084. // injector associated with lazy loading a `Route` array.
  4085. let injector;
  4086. let rawRoutes;
  4087. let requireStandaloneComponents = false;
  4088. if (Array.isArray(factoryOrRoutes)) {
  4089. rawRoutes = factoryOrRoutes;
  4090. requireStandaloneComponents = true;
  4091. }
  4092. else {
  4093. injector = factoryOrRoutes.create(parentInjector).injector;
  4094. // When loading a module that doesn't provide `RouterModule.forChild()` preloader
  4095. // will get stuck in an infinite loop. The child module's Injector will look to
  4096. // its parent `Injector` when it doesn't find any ROUTES so it will return routes
  4097. // for it's parent module instead.
  4098. rawRoutes = injector.get(ROUTES, [], InjectFlags.Self | InjectFlags.Optional).flat();
  4099. }
  4100. const routes = rawRoutes.map(standardizeConfig);
  4101. (typeof ngDevMode === 'undefined' || ngDevMode) &&
  4102. validateConfig(routes, route.path, requireStandaloneComponents);
  4103. return { routes, injector };
  4104. }), finalize(() => {
  4105. this.childrenLoaders.delete(route);
  4106. }));
  4107. // Use custom ConnectableObservable as share in runners pipe increasing the bundle size too much
  4108. const loader = new ConnectableObservable(loadRunner, () => new Subject())
  4109. .pipe(refCount());
  4110. this.childrenLoaders.set(route, loader);
  4111. return loader;
  4112. }
  4113. loadModuleFactoryOrRoutes(loadChildren) {
  4114. return wrapIntoObservable(loadChildren())
  4115. .pipe(map(maybeUnwrapDefaultExport), mergeMap((t) => {
  4116. if (t instanceof NgModuleFactory || Array.isArray(t)) {
  4117. return of(t);
  4118. }
  4119. else {
  4120. return from(this.compiler.compileModuleAsync(t));
  4121. }
  4122. }));
  4123. }
  4124. static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "16.0.4", ngImport: i0, type: RouterConfigLoader, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
  4125. static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "16.0.4", ngImport: i0, type: RouterConfigLoader, providedIn: 'root' }); }
  4126. }
  4127. i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "16.0.4", ngImport: i0, type: RouterConfigLoader, decorators: [{
  4128. type: Injectable,
  4129. args: [{ providedIn: 'root' }]
  4130. }] });
  4131. function isWrappedDefaultExport(value) {
  4132. // We use `in` here with a string key `'default'`, because we expect `DefaultExport` objects to be
  4133. // dynamically imported ES modules with a spec-mandated `default` key. Thus we don't expect that
  4134. // `default` will be a renamed property.
  4135. return value && typeof value === 'object' && 'default' in value;
  4136. }
  4137. function maybeUnwrapDefaultExport(input) {
  4138. // As per `isWrappedDefaultExport`, the `default` key here is generated by the browser and not
  4139. // subject to property renaming, so we reference it with bracket access.
  4140. return isWrappedDefaultExport(input) ? input['default'] : input;
  4141. }
  4142. class NavigationTransitions {
  4143. get hasRequestedNavigation() {
  4144. return this.navigationId !== 0;
  4145. }
  4146. constructor() {
  4147. this.currentNavigation = null;
  4148. this.lastSuccessfulNavigation = null;
  4149. this.events = new Subject();
  4150. this.configLoader = inject(RouterConfigLoader);
  4151. this.environmentInjector = inject(EnvironmentInjector);
  4152. this.urlSerializer = inject(UrlSerializer);
  4153. this.rootContexts = inject(ChildrenOutletContexts);
  4154. this.inputBindingEnabled = inject(INPUT_BINDER, { optional: true }) !== null;
  4155. this.navigationId = 0;
  4156. /**
  4157. * Hook that enables you to pause navigation after the preactivation phase.
  4158. * Used by `RouterModule`.
  4159. *
  4160. * @internal
  4161. */
  4162. this.afterPreactivation = () => of(void 0);
  4163. /** @internal */
  4164. this.rootComponentType = null;
  4165. const onLoadStart = (r) => this.events.next(new RouteConfigLoadStart(r));
  4166. const onLoadEnd = (r) => this.events.next(new RouteConfigLoadEnd(r));
  4167. this.configLoader.onLoadEndListener = onLoadEnd;
  4168. this.configLoader.onLoadStartListener = onLoadStart;
  4169. }
  4170. complete() {
  4171. this.transitions?.complete();
  4172. }
  4173. handleNavigationRequest(request) {
  4174. const id = ++this.navigationId;
  4175. this.transitions?.next({ ...this.transitions.value, ...request, id });
  4176. }
  4177. setupNavigations(router) {
  4178. this.transitions = new BehaviorSubject({
  4179. id: 0,
  4180. currentUrlTree: router.currentUrlTree,
  4181. currentRawUrl: router.currentUrlTree,
  4182. extractedUrl: router.urlHandlingStrategy.extract(router.currentUrlTree),
  4183. urlAfterRedirects: router.urlHandlingStrategy.extract(router.currentUrlTree),
  4184. rawUrl: router.currentUrlTree,
  4185. extras: {},
  4186. resolve: null,
  4187. reject: null,
  4188. promise: Promise.resolve(true),
  4189. source: IMPERATIVE_NAVIGATION,
  4190. restoredState: null,
  4191. currentSnapshot: router.routerState.snapshot,
  4192. targetSnapshot: null,
  4193. currentRouterState: router.routerState,
  4194. targetRouterState: null,
  4195. guards: { canActivateChecks: [], canDeactivateChecks: [] },
  4196. guardsResult: null,
  4197. });
  4198. return this.transitions.pipe(filter(t => t.id !== 0),
  4199. // Extract URL
  4200. map(t => ({ ...t, extractedUrl: router.urlHandlingStrategy.extract(t.rawUrl) })),
  4201. // Using switchMap so we cancel executing navigations when a new one comes in
  4202. switchMap(overallTransitionState => {
  4203. let completed = false;
  4204. let errored = false;
  4205. return of(overallTransitionState)
  4206. .pipe(
  4207. // Store the Navigation object
  4208. tap(t => {
  4209. this.currentNavigation = {
  4210. id: t.id,
  4211. initialUrl: t.rawUrl,
  4212. extractedUrl: t.extractedUrl,
  4213. trigger: t.source,
  4214. extras: t.extras,
  4215. previousNavigation: !this.lastSuccessfulNavigation ? null : {
  4216. ...this.lastSuccessfulNavigation,
  4217. previousNavigation: null,
  4218. },
  4219. };
  4220. }), switchMap(t => {
  4221. const browserUrlTree = router.browserUrlTree.toString();
  4222. const urlTransition = !router.navigated ||
  4223. t.extractedUrl.toString() !== browserUrlTree ||
  4224. // Navigations which succeed or ones which fail and are cleaned up
  4225. // correctly should result in `browserUrlTree` and `currentUrlTree`
  4226. // matching. If this is not the case, assume something went wrong and
  4227. // try processing the URL again.
  4228. browserUrlTree !== router.currentUrlTree.toString();
  4229. const onSameUrlNavigation = t.extras.onSameUrlNavigation ?? router.onSameUrlNavigation;
  4230. if (!urlTransition && onSameUrlNavigation !== 'reload') {
  4231. const reason = (typeof ngDevMode === 'undefined' || ngDevMode) ?
  4232. `Navigation to ${t.rawUrl} was ignored because it is the same as the current Router URL.` :
  4233. '';
  4234. this.events.next(new NavigationSkipped(t.id, router.serializeUrl(overallTransitionState.rawUrl), reason, 0 /* NavigationSkippedCode.IgnoredSameUrlNavigation */));
  4235. router.rawUrlTree = t.rawUrl;
  4236. t.resolve(null);
  4237. return EMPTY;
  4238. }
  4239. if (router.urlHandlingStrategy.shouldProcessUrl(t.rawUrl)) {
  4240. // If the source of the navigation is from a browser event, the URL is
  4241. // already updated. We already need to sync the internal state.
  4242. if (isBrowserTriggeredNavigation(t.source)) {
  4243. router.browserUrlTree = t.extractedUrl;
  4244. }
  4245. return of(t).pipe(
  4246. // Fire NavigationStart event
  4247. switchMap(t => {
  4248. const transition = this.transitions?.getValue();
  4249. this.events.next(new NavigationStart(t.id, this.urlSerializer.serialize(t.extractedUrl), t.source, t.restoredState));
  4250. if (transition !== this.transitions?.getValue()) {
  4251. return EMPTY;
  4252. }
  4253. // This delay is required to match old behavior that forced
  4254. // navigation to always be async
  4255. return Promise.resolve(t);
  4256. }),
  4257. // Recognize
  4258. recognize(this.environmentInjector, this.configLoader, this.rootComponentType, router.config, this.urlSerializer, router.paramsInheritanceStrategy),
  4259. // Update URL if in `eager` update mode
  4260. tap(t => {
  4261. overallTransitionState.targetSnapshot = t.targetSnapshot;
  4262. overallTransitionState.urlAfterRedirects = t.urlAfterRedirects;
  4263. this.currentNavigation = {
  4264. ...this.currentNavigation,
  4265. finalUrl: t.urlAfterRedirects
  4266. };
  4267. if (router.urlUpdateStrategy === 'eager') {
  4268. if (!t.extras.skipLocationChange) {
  4269. const rawUrl = router.urlHandlingStrategy.merge(t.urlAfterRedirects, t.rawUrl);
  4270. router.setBrowserUrl(rawUrl, t);
  4271. }
  4272. router.browserUrlTree = t.urlAfterRedirects;
  4273. }
  4274. // Fire RoutesRecognized
  4275. const routesRecognized = new RoutesRecognized(t.id, this.urlSerializer.serialize(t.extractedUrl), this.urlSerializer.serialize(t.urlAfterRedirects), t.targetSnapshot);
  4276. this.events.next(routesRecognized);
  4277. }));
  4278. }
  4279. else if (urlTransition &&
  4280. router.urlHandlingStrategy.shouldProcessUrl(router.rawUrlTree)) {
  4281. /* When the current URL shouldn't be processed, but the previous one
  4282. * was, we handle this "error condition" by navigating to the
  4283. * previously successful URL, but leaving the URL intact.*/
  4284. const { id, extractedUrl, source, restoredState, extras } = t;
  4285. const navStart = new NavigationStart(id, this.urlSerializer.serialize(extractedUrl), source, restoredState);
  4286. this.events.next(navStart);
  4287. const targetSnapshot = createEmptyState(extractedUrl, this.rootComponentType).snapshot;
  4288. overallTransitionState = {
  4289. ...t,
  4290. targetSnapshot,
  4291. urlAfterRedirects: extractedUrl,
  4292. extras: { ...extras, skipLocationChange: false, replaceUrl: false },
  4293. };
  4294. return of(overallTransitionState);
  4295. }
  4296. else {
  4297. /* When neither the current or previous URL can be processed, do
  4298. * nothing other than update router's internal reference to the
  4299. * current "settled" URL. This way the next navigation will be coming
  4300. * from the current URL in the browser.
  4301. */
  4302. const reason = (typeof ngDevMode === 'undefined' || ngDevMode) ?
  4303. `Navigation was ignored because the UrlHandlingStrategy` +
  4304. ` indicated neither the current URL ${router.rawUrlTree} nor target URL ${t.rawUrl} should be processed.` :
  4305. '';
  4306. this.events.next(new NavigationSkipped(t.id, router.serializeUrl(overallTransitionState.extractedUrl), reason, 1 /* NavigationSkippedCode.IgnoredByUrlHandlingStrategy */));
  4307. router.rawUrlTree = t.rawUrl;
  4308. t.resolve(null);
  4309. return EMPTY;
  4310. }
  4311. }),
  4312. // --- GUARDS ---
  4313. tap(t => {
  4314. const guardsStart = new GuardsCheckStart(t.id, this.urlSerializer.serialize(t.extractedUrl), this.urlSerializer.serialize(t.urlAfterRedirects), t.targetSnapshot);
  4315. this.events.next(guardsStart);
  4316. }), map(t => {
  4317. overallTransitionState = {
  4318. ...t,
  4319. guards: getAllRouteGuards(t.targetSnapshot, t.currentSnapshot, this.rootContexts)
  4320. };
  4321. return overallTransitionState;
  4322. }), checkGuards(this.environmentInjector, (evt) => this.events.next(evt)), tap(t => {
  4323. overallTransitionState.guardsResult = t.guardsResult;
  4324. if (isUrlTree(t.guardsResult)) {
  4325. throw redirectingNavigationError(this.urlSerializer, t.guardsResult);
  4326. }
  4327. const guardsEnd = new GuardsCheckEnd(t.id, this.urlSerializer.serialize(t.extractedUrl), this.urlSerializer.serialize(t.urlAfterRedirects), t.targetSnapshot, !!t.guardsResult);
  4328. this.events.next(guardsEnd);
  4329. }), filter(t => {
  4330. if (!t.guardsResult) {
  4331. router.restoreHistory(t);
  4332. this.cancelNavigationTransition(t, '', 3 /* NavigationCancellationCode.GuardRejected */);
  4333. return false;
  4334. }
  4335. return true;
  4336. }),
  4337. // --- RESOLVE ---
  4338. switchTap(t => {
  4339. if (t.guards.canActivateChecks.length) {
  4340. return of(t).pipe(tap(t => {
  4341. const resolveStart = new ResolveStart(t.id, this.urlSerializer.serialize(t.extractedUrl), this.urlSerializer.serialize(t.urlAfterRedirects), t.targetSnapshot);
  4342. this.events.next(resolveStart);
  4343. }), switchMap(t => {
  4344. let dataResolved = false;
  4345. return of(t).pipe(resolveData(router.paramsInheritanceStrategy, this.environmentInjector), tap({
  4346. next: () => dataResolved = true,
  4347. complete: () => {
  4348. if (!dataResolved) {
  4349. router.restoreHistory(t);
  4350. this.cancelNavigationTransition(t, (typeof ngDevMode === 'undefined' || ngDevMode) ?
  4351. `At least one route resolver didn't emit any value.` :
  4352. '', 2 /* NavigationCancellationCode.NoDataFromResolver */);
  4353. }
  4354. }
  4355. }));
  4356. }), tap(t => {
  4357. const resolveEnd = new ResolveEnd(t.id, this.urlSerializer.serialize(t.extractedUrl), this.urlSerializer.serialize(t.urlAfterRedirects), t.targetSnapshot);
  4358. this.events.next(resolveEnd);
  4359. }));
  4360. }
  4361. return undefined;
  4362. }),
  4363. // --- LOAD COMPONENTS ---
  4364. switchTap((t) => {
  4365. const loadComponents = (route) => {
  4366. const loaders = [];
  4367. if (route.routeConfig?.loadComponent &&
  4368. !route.routeConfig._loadedComponent) {
  4369. loaders.push(this.configLoader.loadComponent(route.routeConfig)
  4370. .pipe(tap(loadedComponent => {
  4371. route.component = loadedComponent;
  4372. }), map(() => void 0)));
  4373. }
  4374. for (const child of route.children) {
  4375. loaders.push(...loadComponents(child));
  4376. }
  4377. return loaders;
  4378. };
  4379. return combineLatest(loadComponents(t.targetSnapshot.root))
  4380. .pipe(defaultIfEmpty(), take(1));
  4381. }), switchTap(() => this.afterPreactivation()), map((t) => {
  4382. const targetRouterState = createRouterState(router.routeReuseStrategy, t.targetSnapshot, t.currentRouterState);
  4383. overallTransitionState = { ...t, targetRouterState };
  4384. return (overallTransitionState);
  4385. }),
  4386. /* Once here, we are about to activate synchronously. The assumption is
  4387. this will succeed, and user code may read from the Router service.
  4388. Therefore before activation, we need to update router properties storing
  4389. the current URL and the RouterState, as well as updated the browser URL.
  4390. All this should happen *before* activating. */
  4391. tap((t) => {
  4392. router.currentUrlTree = t.urlAfterRedirects;
  4393. router.rawUrlTree =
  4394. router.urlHandlingStrategy.merge(t.urlAfterRedirects, t.rawUrl);
  4395. router.routerState =
  4396. t.targetRouterState;
  4397. if (router.urlUpdateStrategy === 'deferred') {
  4398. if (!t.extras.skipLocationChange) {
  4399. router.setBrowserUrl(router.rawUrlTree, t);
  4400. }
  4401. router.browserUrlTree = t.urlAfterRedirects;
  4402. }
  4403. }), activateRoutes(this.rootContexts, router.routeReuseStrategy, (evt) => this.events.next(evt), this.inputBindingEnabled),
  4404. // Ensure that if some observable used to drive the transition doesn't
  4405. // complete, the navigation still finalizes This should never happen, but
  4406. // this is done as a safety measure to avoid surfacing this error (#49567).
  4407. take(1), tap({
  4408. next: (t) => {
  4409. completed = true;
  4410. this.lastSuccessfulNavigation = this.currentNavigation;
  4411. router.navigated = true;
  4412. this.events.next(new NavigationEnd(t.id, this.urlSerializer.serialize(t.extractedUrl), this.urlSerializer.serialize(router.currentUrlTree)));
  4413. router.titleStrategy?.updateTitle(t.targetRouterState.snapshot);
  4414. t.resolve(true);
  4415. },
  4416. complete: () => {
  4417. completed = true;
  4418. }
  4419. }), finalize(() => {
  4420. /* When the navigation stream finishes either through error or success,
  4421. * we set the `completed` or `errored` flag. However, there are some
  4422. * situations where we could get here without either of those being set.
  4423. * For instance, a redirect during NavigationStart. Therefore, this is a
  4424. * catch-all to make sure the NavigationCancel event is fired when a
  4425. * navigation gets cancelled but not caught by other means. */
  4426. if (!completed && !errored) {
  4427. const cancelationReason = (typeof ngDevMode === 'undefined' || ngDevMode) ?
  4428. `Navigation ID ${overallTransitionState
  4429. .id} is not equal to the current navigation id ${this.navigationId}` :
  4430. '';
  4431. this.cancelNavigationTransition(overallTransitionState, cancelationReason, 1 /* NavigationCancellationCode.SupersededByNewNavigation */);
  4432. }
  4433. // Only clear current navigation if it is still set to the one that
  4434. // finalized.
  4435. if (this.currentNavigation?.id === overallTransitionState.id) {
  4436. this.currentNavigation = null;
  4437. }
  4438. }), catchError((e) => {
  4439. errored = true;
  4440. /* This error type is issued during Redirect, and is handled as a
  4441. * cancellation rather than an error. */
  4442. if (isNavigationCancelingError$1(e)) {
  4443. if (!isRedirectingNavigationCancelingError$1(e)) {
  4444. // Set property only if we're not redirecting. If we landed on a page
  4445. // and redirect to `/` route, the new navigation is going to see the
  4446. // `/` isn't a change from the default currentUrlTree and won't
  4447. // navigate. This is only applicable with initial navigation, so
  4448. // setting `navigated` only when not redirecting resolves this
  4449. // scenario.
  4450. router.navigated = true;
  4451. router.restoreHistory(overallTransitionState, true);
  4452. }
  4453. const navCancel = new NavigationCancel(overallTransitionState.id, this.urlSerializer.serialize(overallTransitionState.extractedUrl), e.message, e.cancellationCode);
  4454. this.events.next(navCancel);
  4455. // When redirecting, we need to delay resolving the navigation
  4456. // promise and push it to the redirect navigation
  4457. if (!isRedirectingNavigationCancelingError$1(e)) {
  4458. overallTransitionState.resolve(false);
  4459. }
  4460. else {
  4461. const mergedTree = router.urlHandlingStrategy.merge(e.url, router.rawUrlTree);
  4462. const extras = {
  4463. skipLocationChange: overallTransitionState.extras.skipLocationChange,
  4464. // The URL is already updated at this point if we have 'eager' URL
  4465. // updates or if the navigation was triggered by the browser (back
  4466. // button, URL bar, etc). We want to replace that item in history
  4467. // if the navigation is rejected.
  4468. replaceUrl: router.urlUpdateStrategy === 'eager' ||
  4469. isBrowserTriggeredNavigation(overallTransitionState.source)
  4470. };
  4471. router.scheduleNavigation(mergedTree, IMPERATIVE_NAVIGATION, null, extras, {
  4472. resolve: overallTransitionState.resolve,
  4473. reject: overallTransitionState.reject,
  4474. promise: overallTransitionState.promise
  4475. });
  4476. }
  4477. /* All other errors should reset to the router's internal URL reference
  4478. * to the pre-error state. */
  4479. }
  4480. else {
  4481. router.restoreHistory(overallTransitionState, true);
  4482. const navError = new NavigationError(overallTransitionState.id, this.urlSerializer.serialize(overallTransitionState.extractedUrl), e, overallTransitionState.targetSnapshot ?? undefined);
  4483. this.events.next(navError);
  4484. try {
  4485. overallTransitionState.resolve(router.errorHandler(e));
  4486. }
  4487. catch (ee) {
  4488. overallTransitionState.reject(ee);
  4489. }
  4490. }
  4491. return EMPTY;
  4492. }));
  4493. // casting because `pipe` returns observable({}) when called with 8+ arguments
  4494. }));
  4495. }
  4496. cancelNavigationTransition(t, reason, code) {
  4497. const navCancel = new NavigationCancel(t.id, this.urlSerializer.serialize(t.extractedUrl), reason, code);
  4498. this.events.next(navCancel);
  4499. t.resolve(false);
  4500. }
  4501. static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "16.0.4", ngImport: i0, type: NavigationTransitions, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
  4502. static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "16.0.4", ngImport: i0, type: NavigationTransitions, providedIn: 'root' }); }
  4503. }
  4504. i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "16.0.4", ngImport: i0, type: NavigationTransitions, decorators: [{
  4505. type: Injectable,
  4506. args: [{ providedIn: 'root' }]
  4507. }], ctorParameters: function () { return []; } });
  4508. function isBrowserTriggeredNavigation(source) {
  4509. return source !== IMPERATIVE_NAVIGATION;
  4510. }
  4511. /**
  4512. * Provides a strategy for setting the page title after a router navigation.
  4513. *
  4514. * The built-in implementation traverses the router state snapshot and finds the deepest primary
  4515. * outlet with `title` property. Given the `Routes` below, navigating to
  4516. * `/base/child(popup:aux)` would result in the document title being set to "child".
  4517. * ```
  4518. * [
  4519. * {path: 'base', title: 'base', children: [
  4520. * {path: 'child', title: 'child'},
  4521. * ],
  4522. * {path: 'aux', outlet: 'popup', title: 'popupTitle'}
  4523. * ]
  4524. * ```
  4525. *
  4526. * This class can be used as a base class for custom title strategies. That is, you can create your
  4527. * own class that extends the `TitleStrategy`. Note that in the above example, the `title`
  4528. * from the named outlet is never used. However, a custom strategy might be implemented to
  4529. * incorporate titles in named outlets.
  4530. *
  4531. * @publicApi
  4532. * @see [Page title guide](guide/router#setting-the-page-title)
  4533. */
  4534. class TitleStrategy {
  4535. /**
  4536. * @returns The `title` of the deepest primary route.
  4537. */
  4538. buildTitle(snapshot) {
  4539. let pageTitle;
  4540. let route = snapshot.root;
  4541. while (route !== undefined) {
  4542. pageTitle = this.getResolvedTitleForRoute(route) ?? pageTitle;
  4543. route = route.children.find(child => child.outlet === PRIMARY_OUTLET);
  4544. }
  4545. return pageTitle;
  4546. }
  4547. /**
  4548. * Given an `ActivatedRouteSnapshot`, returns the final value of the
  4549. * `Route.title` property, which can either be a static string or a resolved value.
  4550. */
  4551. getResolvedTitleForRoute(snapshot) {
  4552. return snapshot.data[RouteTitleKey];
  4553. }
  4554. static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "16.0.4", ngImport: i0, type: TitleStrategy, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
  4555. static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "16.0.4", ngImport: i0, type: TitleStrategy, providedIn: 'root', useFactory: () => inject(DefaultTitleStrategy) }); }
  4556. }
  4557. i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "16.0.4", ngImport: i0, type: TitleStrategy, decorators: [{
  4558. type: Injectable,
  4559. args: [{ providedIn: 'root', useFactory: () => inject(DefaultTitleStrategy) }]
  4560. }] });
  4561. /**
  4562. * The default `TitleStrategy` used by the router that updates the title using the `Title` service.
  4563. */
  4564. class DefaultTitleStrategy extends TitleStrategy {
  4565. constructor(title) {
  4566. super();
  4567. this.title = title;
  4568. }
  4569. /**
  4570. * Sets the title of the browser to the given value.
  4571. *
  4572. * @param title The `pageTitle` from the deepest primary route.
  4573. */
  4574. updateTitle(snapshot) {
  4575. const title = this.buildTitle(snapshot);
  4576. if (title !== undefined) {
  4577. this.title.setTitle(title);
  4578. }
  4579. }
  4580. static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "16.0.4", ngImport: i0, type: DefaultTitleStrategy, deps: [{ token: i1.Title }], target: i0.ɵɵFactoryTarget.Injectable }); }
  4581. static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "16.0.4", ngImport: i0, type: DefaultTitleStrategy, providedIn: 'root' }); }
  4582. }
  4583. i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "16.0.4", ngImport: i0, type: DefaultTitleStrategy, decorators: [{
  4584. type: Injectable,
  4585. args: [{ providedIn: 'root' }]
  4586. }], ctorParameters: function () { return [{ type: i1.Title }]; } });
  4587. /**
  4588. * @description
  4589. *
  4590. * Provides a way to customize when activated routes get reused.
  4591. *
  4592. * @publicApi
  4593. */
  4594. class RouteReuseStrategy {
  4595. static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "16.0.4", ngImport: i0, type: RouteReuseStrategy, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
  4596. static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "16.0.4", ngImport: i0, type: RouteReuseStrategy, providedIn: 'root', useFactory: () => inject(DefaultRouteReuseStrategy) }); }
  4597. }
  4598. i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "16.0.4", ngImport: i0, type: RouteReuseStrategy, decorators: [{
  4599. type: Injectable,
  4600. args: [{ providedIn: 'root', useFactory: () => inject(DefaultRouteReuseStrategy) }]
  4601. }] });
  4602. /**
  4603. * @description
  4604. *
  4605. * This base route reuse strategy only reuses routes when the matched router configs are
  4606. * identical. This prevents components from being destroyed and recreated
  4607. * when just the route parameters, query parameters or fragment change
  4608. * (that is, the existing component is _reused_).
  4609. *
  4610. * This strategy does not store any routes for later reuse.
  4611. *
  4612. * Angular uses this strategy by default.
  4613. *
  4614. *
  4615. * It can be used as a base class for custom route reuse strategies, i.e. you can create your own
  4616. * class that extends the `BaseRouteReuseStrategy` one.
  4617. * @publicApi
  4618. */
  4619. class BaseRouteReuseStrategy {
  4620. /**
  4621. * Whether the given route should detach for later reuse.
  4622. * Always returns false for `BaseRouteReuseStrategy`.
  4623. * */
  4624. shouldDetach(route) {
  4625. return false;
  4626. }
  4627. /**
  4628. * A no-op; the route is never stored since this strategy never detaches routes for later re-use.
  4629. */
  4630. store(route, detachedTree) { }
  4631. /** Returns `false`, meaning the route (and its subtree) is never reattached */
  4632. shouldAttach(route) {
  4633. return false;
  4634. }
  4635. /** Returns `null` because this strategy does not store routes for later re-use. */
  4636. retrieve(route) {
  4637. return null;
  4638. }
  4639. /**
  4640. * Determines if a route should be reused.
  4641. * This strategy returns `true` when the future route config and current route config are
  4642. * identical.
  4643. */
  4644. shouldReuseRoute(future, curr) {
  4645. return future.routeConfig === curr.routeConfig;
  4646. }
  4647. }
  4648. class DefaultRouteReuseStrategy extends BaseRouteReuseStrategy {
  4649. static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "16.0.4", ngImport: i0, type: DefaultRouteReuseStrategy, deps: null, target: i0.ɵɵFactoryTarget.Injectable }); }
  4650. static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "16.0.4", ngImport: i0, type: DefaultRouteReuseStrategy, providedIn: 'root' }); }
  4651. }
  4652. i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "16.0.4", ngImport: i0, type: DefaultRouteReuseStrategy, decorators: [{
  4653. type: Injectable,
  4654. args: [{ providedIn: 'root' }]
  4655. }] });
  4656. /**
  4657. * A [DI token](guide/glossary/#di-token) for the router service.
  4658. *
  4659. * @publicApi
  4660. */
  4661. const ROUTER_CONFIGURATION = new InjectionToken((typeof ngDevMode === 'undefined' || ngDevMode) ? 'router config' : '', {
  4662. providedIn: 'root',
  4663. factory: () => ({}),
  4664. });
  4665. /**
  4666. * @description
  4667. *
  4668. * Provides a way to migrate AngularJS applications to Angular.
  4669. *
  4670. * @publicApi
  4671. */
  4672. class UrlHandlingStrategy {
  4673. static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "16.0.4", ngImport: i0, type: UrlHandlingStrategy, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
  4674. static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "16.0.4", ngImport: i0, type: UrlHandlingStrategy, providedIn: 'root', useFactory: () => inject(DefaultUrlHandlingStrategy) }); }
  4675. }
  4676. i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "16.0.4", ngImport: i0, type: UrlHandlingStrategy, decorators: [{
  4677. type: Injectable,
  4678. args: [{ providedIn: 'root', useFactory: () => inject(DefaultUrlHandlingStrategy) }]
  4679. }] });
  4680. /**
  4681. * @publicApi
  4682. */
  4683. class DefaultUrlHandlingStrategy {
  4684. shouldProcessUrl(url) {
  4685. return true;
  4686. }
  4687. extract(url) {
  4688. return url;
  4689. }
  4690. merge(newUrlPart, wholeUrl) {
  4691. return newUrlPart;
  4692. }
  4693. static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "16.0.4", ngImport: i0, type: DefaultUrlHandlingStrategy, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
  4694. static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "16.0.4", ngImport: i0, type: DefaultUrlHandlingStrategy, providedIn: 'root' }); }
  4695. }
  4696. i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "16.0.4", ngImport: i0, type: DefaultUrlHandlingStrategy, decorators: [{
  4697. type: Injectable,
  4698. args: [{ providedIn: 'root' }]
  4699. }] });
  4700. var NavigationResult;
  4701. (function (NavigationResult) {
  4702. NavigationResult[NavigationResult["COMPLETE"] = 0] = "COMPLETE";
  4703. NavigationResult[NavigationResult["FAILED"] = 1] = "FAILED";
  4704. NavigationResult[NavigationResult["REDIRECTING"] = 2] = "REDIRECTING";
  4705. })(NavigationResult || (NavigationResult = {}));
  4706. /**
  4707. * Performs the given action once the router finishes its next/current navigation.
  4708. *
  4709. * The navigation is considered complete under the following conditions:
  4710. * - `NavigationCancel` event emits and the code is not `NavigationCancellationCode.Redirect` or
  4711. * `NavigationCancellationCode.SupersededByNewNavigation`. In these cases, the
  4712. * redirecting/superseding navigation must finish.
  4713. * - `NavigationError`, `NavigationEnd`, or `NavigationSkipped` event emits
  4714. */
  4715. function afterNextNavigation(router, action) {
  4716. router.events
  4717. .pipe(filter((e) => e instanceof NavigationEnd || e instanceof NavigationCancel ||
  4718. e instanceof NavigationError || e instanceof NavigationSkipped), map(e => {
  4719. if (e instanceof NavigationEnd || e instanceof NavigationSkipped) {
  4720. return NavigationResult.COMPLETE;
  4721. }
  4722. const redirecting = e instanceof NavigationCancel ?
  4723. (e.code === 0 /* NavigationCancellationCode.Redirect */ ||
  4724. e.code === 1 /* NavigationCancellationCode.SupersededByNewNavigation */) :
  4725. false;
  4726. return redirecting ? NavigationResult.REDIRECTING : NavigationResult.FAILED;
  4727. }), filter((result) => result !== NavigationResult.REDIRECTING), take(1))
  4728. .subscribe(() => {
  4729. action();
  4730. });
  4731. }
  4732. function defaultErrorHandler(error) {
  4733. throw error;
  4734. }
  4735. function defaultMalformedUriErrorHandler(error, urlSerializer, url) {
  4736. return urlSerializer.parse('/');
  4737. }
  4738. /**
  4739. * The equivalent `IsActiveMatchOptions` options for `Router.isActive` is called with `true`
  4740. * (exact = true).
  4741. */
  4742. const exactMatchOptions = {
  4743. paths: 'exact',
  4744. fragment: 'ignored',
  4745. matrixParams: 'ignored',
  4746. queryParams: 'exact'
  4747. };
  4748. /**
  4749. * The equivalent `IsActiveMatchOptions` options for `Router.isActive` is called with `false`
  4750. * (exact = false).
  4751. */
  4752. const subsetMatchOptions = {
  4753. paths: 'subset',
  4754. fragment: 'ignored',
  4755. matrixParams: 'ignored',
  4756. queryParams: 'subset'
  4757. };
  4758. /**
  4759. * @description
  4760. *
  4761. * A service that provides navigation among views and URL manipulation capabilities.
  4762. *
  4763. * @see `Route`.
  4764. * @see [Routing and Navigation Guide](guide/router).
  4765. *
  4766. * @ngModule RouterModule
  4767. *
  4768. * @publicApi
  4769. */
  4770. class Router {
  4771. // TODO(b/260747083): This should not exist and navigationId should be private in
  4772. // `NavigationTransitions`
  4773. get navigationId() {
  4774. return this.navigationTransitions.navigationId;
  4775. }
  4776. /**
  4777. * The ɵrouterPageId of whatever page is currently active in the browser history. This is
  4778. * important for computing the target page id for new navigations because we need to ensure each
  4779. * page id in the browser history is 1 more than the previous entry.
  4780. */
  4781. get browserPageId() {
  4782. if (this.canceledNavigationResolution !== 'computed') {
  4783. return undefined;
  4784. }
  4785. return this.location.getState()?.ɵrouterPageId;
  4786. }
  4787. /**
  4788. * An event stream for routing events.
  4789. */
  4790. get events() {
  4791. // TODO(atscott): This _should_ be events.asObservable(). However, this change requires internal
  4792. // cleanup: tests are doing `(route.events as Subject<Event>).next(...)`. This isn't
  4793. // allowed/supported but we still have to fix these or file bugs against the teams before making
  4794. // the change.
  4795. return this.navigationTransitions.events;
  4796. }
  4797. constructor() {
  4798. this.disposed = false;
  4799. /**
  4800. * The id of the currently active page in the router.
  4801. * Updated to the transition's target id on a successful navigation.
  4802. *
  4803. * This is used to track what page the router last activated. When an attempted navigation fails,
  4804. * the router can then use this to compute how to restore the state back to the previously active
  4805. * page.
  4806. */
  4807. this.currentPageId = 0;
  4808. this.console = inject(ɵConsole);
  4809. this.isNgZoneEnabled = false;
  4810. this.options = inject(ROUTER_CONFIGURATION, { optional: true }) || {};
  4811. this.pendingTasks = inject(ɵInitialRenderPendingTasks);
  4812. /**
  4813. * A handler for navigation errors in this NgModule.
  4814. *
  4815. * @deprecated Subscribe to the `Router` events and watch for `NavigationError` instead.
  4816. * `provideRouter` has the `withNavigationErrorHandler` feature to make this easier.
  4817. * @see `withNavigationErrorHandler`
  4818. */
  4819. this.errorHandler = this.options.errorHandler || defaultErrorHandler;
  4820. /**
  4821. * A handler for errors thrown by `Router.parseUrl(url)`
  4822. * when `url` contains an invalid character.
  4823. * The most common case is a `%` sign
  4824. * that's not encoded and is not part of a percent encoded sequence.
  4825. *
  4826. * @deprecated URI parsing errors should be handled in the `UrlSerializer`.
  4827. *
  4828. * @see `RouterModule`
  4829. */
  4830. this.malformedUriErrorHandler = this.options.malformedUriErrorHandler || defaultMalformedUriErrorHandler;
  4831. /**
  4832. * True if at least one navigation event has occurred,
  4833. * false otherwise.
  4834. */
  4835. this.navigated = false;
  4836. this.lastSuccessfulId = -1;
  4837. /**
  4838. * A strategy for extracting and merging URLs.
  4839. * Used for AngularJS to Angular migrations.
  4840. *
  4841. * @deprecated Configure using `providers` instead:
  4842. * `{provide: UrlHandlingStrategy, useClass: MyStrategy}`.
  4843. */
  4844. this.urlHandlingStrategy = inject(UrlHandlingStrategy);
  4845. /**
  4846. * A strategy for re-using routes.
  4847. *
  4848. * @deprecated Configure using `providers` instead:
  4849. * `{provide: RouteReuseStrategy, useClass: MyStrategy}`.
  4850. */
  4851. this.routeReuseStrategy = inject(RouteReuseStrategy);
  4852. /**
  4853. * A strategy for setting the title based on the `routerState`.
  4854. *
  4855. * @deprecated Configure using `providers` instead:
  4856. * `{provide: TitleStrategy, useClass: MyStrategy}`.
  4857. */
  4858. this.titleStrategy = inject(TitleStrategy);
  4859. /**
  4860. * How to handle a navigation request to the current URL.
  4861. *
  4862. *
  4863. * @deprecated Configure this through `provideRouter` or `RouterModule.forRoot` instead.
  4864. * @see `withRouterConfig`
  4865. * @see `provideRouter`
  4866. * @see `RouterModule`
  4867. */
  4868. this.onSameUrlNavigation = this.options.onSameUrlNavigation || 'ignore';
  4869. /**
  4870. * How to merge parameters, data, resolved data, and title from parent to child
  4871. * routes. One of:
  4872. *
  4873. * - `'emptyOnly'` : Inherit parent parameters, data, and resolved data
  4874. * for path-less or component-less routes.
  4875. * - `'always'` : Inherit parent parameters, data, and resolved data
  4876. * for all child routes.
  4877. *
  4878. * @deprecated Configure this through `provideRouter` or `RouterModule.forRoot` instead.
  4879. * @see `withRouterConfig`
  4880. * @see `provideRouter`
  4881. * @see `RouterModule`
  4882. */
  4883. this.paramsInheritanceStrategy = this.options.paramsInheritanceStrategy || 'emptyOnly';
  4884. /**
  4885. * Determines when the router updates the browser URL.
  4886. * By default (`"deferred"`), updates the browser URL after navigation has finished.
  4887. * Set to `'eager'` to update the browser URL at the beginning of navigation.
  4888. * You can choose to update early so that, if navigation fails,
  4889. * you can show an error message with the URL that failed.
  4890. *
  4891. * @deprecated Configure this through `provideRouter` or `RouterModule.forRoot` instead.
  4892. * @see `withRouterConfig`
  4893. * @see `provideRouter`
  4894. * @see `RouterModule`
  4895. */
  4896. this.urlUpdateStrategy = this.options.urlUpdateStrategy || 'deferred';
  4897. /**
  4898. * Configures how the Router attempts to restore state when a navigation is cancelled.
  4899. *
  4900. * 'replace' - Always uses `location.replaceState` to set the browser state to the state of the
  4901. * router before the navigation started. This means that if the URL of the browser is updated
  4902. * _before_ the navigation is canceled, the Router will simply replace the item in history rather
  4903. * than trying to restore to the previous location in the session history. This happens most
  4904. * frequently with `urlUpdateStrategy: 'eager'` and navigations with the browser back/forward
  4905. * buttons.
  4906. *
  4907. * 'computed' - Will attempt to return to the same index in the session history that corresponds
  4908. * to the Angular route when the navigation gets cancelled. For example, if the browser back
  4909. * button is clicked and the navigation is cancelled, the Router will trigger a forward navigation
  4910. * and vice versa.
  4911. *
  4912. * Note: the 'computed' option is incompatible with any `UrlHandlingStrategy` which only
  4913. * handles a portion of the URL because the history restoration navigates to the previous place in
  4914. * the browser history rather than simply resetting a portion of the URL.
  4915. *
  4916. * The default value is `replace`.
  4917. *
  4918. * @deprecated Configure this through `provideRouter` or `RouterModule.forRoot` instead.
  4919. * @see `withRouterConfig`
  4920. * @see `provideRouter`
  4921. * @see `RouterModule`
  4922. */
  4923. this.canceledNavigationResolution = this.options.canceledNavigationResolution || 'replace';
  4924. this.config = inject(ROUTES, { optional: true })?.flat() ?? [];
  4925. this.navigationTransitions = inject(NavigationTransitions);
  4926. this.urlSerializer = inject(UrlSerializer);
  4927. this.location = inject(Location);
  4928. /**
  4929. * Indicates whether the the application has opted in to binding Router data to component inputs.
  4930. *
  4931. * This option is enabled by the `withComponentInputBinding` feature of `provideRouter` or
  4932. * `bindToComponentInputs` in the `ExtraOptions` of `RouterModule.forRoot`.
  4933. */
  4934. this.componentInputBindingEnabled = !!inject(INPUT_BINDER, { optional: true });
  4935. this.isNgZoneEnabled = inject(NgZone) instanceof NgZone && NgZone.isInAngularZone();
  4936. this.resetConfig(this.config);
  4937. this.currentUrlTree = new UrlTree();
  4938. this.rawUrlTree = this.currentUrlTree;
  4939. this.browserUrlTree = this.currentUrlTree;
  4940. this.routerState = createEmptyState(this.currentUrlTree, null);
  4941. this.navigationTransitions.setupNavigations(this).subscribe(t => {
  4942. this.lastSuccessfulId = t.id;
  4943. this.currentPageId = this.browserPageId ?? 0;
  4944. }, e => {
  4945. this.console.warn(`Unhandled Navigation Error: ${e}`);
  4946. });
  4947. }
  4948. /** @internal */
  4949. resetRootComponentType(rootComponentType) {
  4950. // TODO: vsavkin router 4.0 should make the root component set to null
  4951. // this will simplify the lifecycle of the router.
  4952. this.routerState.root.component = rootComponentType;
  4953. this.navigationTransitions.rootComponentType = rootComponentType;
  4954. }
  4955. /**
  4956. * Sets up the location change listener and performs the initial navigation.
  4957. */
  4958. initialNavigation() {
  4959. this.setUpLocationChangeListener();
  4960. if (!this.navigationTransitions.hasRequestedNavigation) {
  4961. const state = this.location.getState();
  4962. this.navigateToSyncWithBrowser(this.location.path(true), IMPERATIVE_NAVIGATION, state);
  4963. }
  4964. }
  4965. /**
  4966. * Sets up the location change listener. This listener detects navigations triggered from outside
  4967. * the Router (the browser back/forward buttons, for example) and schedules a corresponding Router
  4968. * navigation so that the correct events, guards, etc. are triggered.
  4969. */
  4970. setUpLocationChangeListener() {
  4971. // Don't need to use Zone.wrap any more, because zone.js
  4972. // already patch onPopState, so location change callback will
  4973. // run into ngZone
  4974. if (!this.locationSubscription) {
  4975. this.locationSubscription = this.location.subscribe(event => {
  4976. const source = event['type'] === 'popstate' ? 'popstate' : 'hashchange';
  4977. if (source === 'popstate') {
  4978. // The `setTimeout` was added in #12160 and is likely to support Angular/AngularJS
  4979. // hybrid apps.
  4980. setTimeout(() => {
  4981. this.navigateToSyncWithBrowser(event['url'], source, event.state);
  4982. }, 0);
  4983. }
  4984. });
  4985. }
  4986. }
  4987. /**
  4988. * Schedules a router navigation to synchronize Router state with the browser state.
  4989. *
  4990. * This is done as a response to a popstate event and the initial navigation. These
  4991. * two scenarios represent times when the browser URL/state has been updated and
  4992. * the Router needs to respond to ensure its internal state matches.
  4993. */
  4994. navigateToSyncWithBrowser(url, source, state) {
  4995. const extras = { replaceUrl: true };
  4996. // TODO: restoredState should always include the entire state, regardless
  4997. // of navigationId. This requires a breaking change to update the type on
  4998. // NavigationStart’s restoredState, which currently requires navigationId
  4999. // to always be present. The Router used to only restore history state if
  5000. // a navigationId was present.
  5001. // The stored navigationId is used by the RouterScroller to retrieve the scroll
  5002. // position for the page.
  5003. const restoredState = state?.navigationId ? state : null;
  5004. // Separate to NavigationStart.restoredState, we must also restore the state to
  5005. // history.state and generate a new navigationId, since it will be overwritten
  5006. if (state) {
  5007. const stateCopy = { ...state };
  5008. delete stateCopy.navigationId;
  5009. delete stateCopy.ɵrouterPageId;
  5010. if (Object.keys(stateCopy).length !== 0) {
  5011. extras.state = stateCopy;
  5012. }
  5013. }
  5014. const urlTree = this.parseUrl(url);
  5015. this.scheduleNavigation(urlTree, source, restoredState, extras);
  5016. }
  5017. /** The current URL. */
  5018. get url() {
  5019. return this.serializeUrl(this.currentUrlTree);
  5020. }
  5021. /**
  5022. * Returns the current `Navigation` object when the router is navigating,
  5023. * and `null` when idle.
  5024. */
  5025. getCurrentNavigation() {
  5026. return this.navigationTransitions.currentNavigation;
  5027. }
  5028. /**
  5029. * The `Navigation` object of the most recent navigation to succeed and `null` if there
  5030. * has not been a successful navigation yet.
  5031. */
  5032. get lastSuccessfulNavigation() {
  5033. return this.navigationTransitions.lastSuccessfulNavigation;
  5034. }
  5035. /**
  5036. * Resets the route configuration used for navigation and generating links.
  5037. *
  5038. * @param config The route array for the new configuration.
  5039. *
  5040. * @usageNotes
  5041. *
  5042. * ```
  5043. * router.resetConfig([
  5044. * { path: 'team/:id', component: TeamCmp, children: [
  5045. * { path: 'simple', component: SimpleCmp },
  5046. * { path: 'user/:name', component: UserCmp }
  5047. * ]}
  5048. * ]);
  5049. * ```
  5050. */
  5051. resetConfig(config) {
  5052. (typeof ngDevMode === 'undefined' || ngDevMode) && validateConfig(config);
  5053. this.config = config.map(standardizeConfig);
  5054. this.navigated = false;
  5055. this.lastSuccessfulId = -1;
  5056. }
  5057. /** @nodoc */
  5058. ngOnDestroy() {
  5059. this.dispose();
  5060. }
  5061. /** Disposes of the router. */
  5062. dispose() {
  5063. this.navigationTransitions.complete();
  5064. if (this.locationSubscription) {
  5065. this.locationSubscription.unsubscribe();
  5066. this.locationSubscription = undefined;
  5067. }
  5068. this.disposed = true;
  5069. }
  5070. /**
  5071. * Appends URL segments to the current URL tree to create a new URL tree.
  5072. *
  5073. * @param commands An array of URL fragments with which to construct the new URL tree.
  5074. * If the path is static, can be the literal URL string. For a dynamic path, pass an array of path
  5075. * segments, followed by the parameters for each segment.
  5076. * The fragments are applied to the current URL tree or the one provided in the `relativeTo`
  5077. * property of the options object, if supplied.
  5078. * @param navigationExtras Options that control the navigation strategy.
  5079. * @returns The new URL tree.
  5080. *
  5081. * @usageNotes
  5082. *
  5083. * ```
  5084. * // create /team/33/user/11
  5085. * router.createUrlTree(['/team', 33, 'user', 11]);
  5086. *
  5087. * // create /team/33;expand=true/user/11
  5088. * router.createUrlTree(['/team', 33, {expand: true}, 'user', 11]);
  5089. *
  5090. * // you can collapse static segments like this (this works only with the first passed-in value):
  5091. * router.createUrlTree(['/team/33/user', userId]);
  5092. *
  5093. * // If the first segment can contain slashes, and you do not want the router to split it,
  5094. * // you can do the following:
  5095. * router.createUrlTree([{segmentPath: '/one/two'}]);
  5096. *
  5097. * // create /team/33/(user/11//right:chat)
  5098. * router.createUrlTree(['/team', 33, {outlets: {primary: 'user/11', right: 'chat'}}]);
  5099. *
  5100. * // remove the right secondary node
  5101. * router.createUrlTree(['/team', 33, {outlets: {primary: 'user/11', right: null}}]);
  5102. *
  5103. * // assuming the current url is `/team/33/user/11` and the route points to `user/11`
  5104. *
  5105. * // navigate to /team/33/user/11/details
  5106. * router.createUrlTree(['details'], {relativeTo: route});
  5107. *
  5108. * // navigate to /team/33/user/22
  5109. * router.createUrlTree(['../22'], {relativeTo: route});
  5110. *
  5111. * // navigate to /team/44/user/22
  5112. * router.createUrlTree(['../../team/44/user/22'], {relativeTo: route});
  5113. *
  5114. * Note that a value of `null` or `undefined` for `relativeTo` indicates that the
  5115. * tree should be created relative to the root.
  5116. * ```
  5117. */
  5118. createUrlTree(commands, navigationExtras = {}) {
  5119. const { relativeTo, queryParams, fragment, queryParamsHandling, preserveFragment } = navigationExtras;
  5120. const f = preserveFragment ? this.currentUrlTree.fragment : fragment;
  5121. let q = null;
  5122. switch (queryParamsHandling) {
  5123. case 'merge':
  5124. q = { ...this.currentUrlTree.queryParams, ...queryParams };
  5125. break;
  5126. case 'preserve':
  5127. q = this.currentUrlTree.queryParams;
  5128. break;
  5129. default:
  5130. q = queryParams || null;
  5131. }
  5132. if (q !== null) {
  5133. q = this.removeEmptyProps(q);
  5134. }
  5135. let relativeToUrlSegmentGroup;
  5136. try {
  5137. const relativeToSnapshot = relativeTo ? relativeTo.snapshot : this.routerState.snapshot.root;
  5138. relativeToUrlSegmentGroup = createSegmentGroupFromRoute(relativeToSnapshot);
  5139. }
  5140. catch (e) {
  5141. // This is strictly for backwards compatibility with tests that create
  5142. // invalid `ActivatedRoute` mocks.
  5143. // Note: the difference between having this fallback for invalid `ActivatedRoute` setups and
  5144. // just throwing is ~500 test failures. Fixing all of those tests by hand is not feasible at
  5145. // the moment.
  5146. if (typeof commands[0] !== 'string' || !commands[0].startsWith('/')) {
  5147. // Navigations that were absolute in the old way of creating UrlTrees
  5148. // would still work because they wouldn't attempt to match the
  5149. // segments in the `ActivatedRoute` to the `currentUrlTree` but
  5150. // instead just replace the root segment with the navigation result.
  5151. // Non-absolute navigations would fail to apply the commands because
  5152. // the logic could not find the segment to replace (so they'd act like there were no
  5153. // commands).
  5154. commands = [];
  5155. }
  5156. relativeToUrlSegmentGroup = this.currentUrlTree.root;
  5157. }
  5158. return createUrlTreeFromSegmentGroup(relativeToUrlSegmentGroup, commands, q, f ?? null);
  5159. }
  5160. /**
  5161. * Navigates to a view using an absolute route path.
  5162. *
  5163. * @param url An absolute path for a defined route. The function does not apply any delta to the
  5164. * current URL.
  5165. * @param extras An object containing properties that modify the navigation strategy.
  5166. *
  5167. * @returns A Promise that resolves to 'true' when navigation succeeds,
  5168. * to 'false' when navigation fails, or is rejected on error.
  5169. *
  5170. * @usageNotes
  5171. *
  5172. * The following calls request navigation to an absolute path.
  5173. *
  5174. * ```
  5175. * router.navigateByUrl("/team/33/user/11");
  5176. *
  5177. * // Navigate without updating the URL
  5178. * router.navigateByUrl("/team/33/user/11", { skipLocationChange: true });
  5179. * ```
  5180. *
  5181. * @see [Routing and Navigation guide](guide/router)
  5182. *
  5183. */
  5184. navigateByUrl(url, extras = {
  5185. skipLocationChange: false
  5186. }) {
  5187. if (typeof ngDevMode === 'undefined' || ngDevMode) {
  5188. if (this.isNgZoneEnabled && !NgZone.isInAngularZone()) {
  5189. this.console.warn(`Navigation triggered outside Angular zone, did you forget to call 'ngZone.run()'?`);
  5190. }
  5191. }
  5192. const urlTree = isUrlTree(url) ? url : this.parseUrl(url);
  5193. const mergedTree = this.urlHandlingStrategy.merge(urlTree, this.rawUrlTree);
  5194. return this.scheduleNavigation(mergedTree, IMPERATIVE_NAVIGATION, null, extras);
  5195. }
  5196. /**
  5197. * Navigate based on the provided array of commands and a starting point.
  5198. * If no starting route is provided, the navigation is absolute.
  5199. *
  5200. * @param commands An array of URL fragments with which to construct the target URL.
  5201. * If the path is static, can be the literal URL string. For a dynamic path, pass an array of path
  5202. * segments, followed by the parameters for each segment.
  5203. * The fragments are applied to the current URL or the one provided in the `relativeTo` property
  5204. * of the options object, if supplied.
  5205. * @param extras An options object that determines how the URL should be constructed or
  5206. * interpreted.
  5207. *
  5208. * @returns A Promise that resolves to `true` when navigation succeeds, to `false` when navigation
  5209. * fails,
  5210. * or is rejected on error.
  5211. *
  5212. * @usageNotes
  5213. *
  5214. * The following calls request navigation to a dynamic route path relative to the current URL.
  5215. *
  5216. * ```
  5217. * router.navigate(['team', 33, 'user', 11], {relativeTo: route});
  5218. *
  5219. * // Navigate without updating the URL, overriding the default behavior
  5220. * router.navigate(['team', 33, 'user', 11], {relativeTo: route, skipLocationChange: true});
  5221. * ```
  5222. *
  5223. * @see [Routing and Navigation guide](guide/router)
  5224. *
  5225. */
  5226. navigate(commands, extras = { skipLocationChange: false }) {
  5227. validateCommands(commands);
  5228. return this.navigateByUrl(this.createUrlTree(commands, extras), extras);
  5229. }
  5230. /** Serializes a `UrlTree` into a string */
  5231. serializeUrl(url) {
  5232. return this.urlSerializer.serialize(url);
  5233. }
  5234. /** Parses a string into a `UrlTree` */
  5235. parseUrl(url) {
  5236. let urlTree;
  5237. try {
  5238. urlTree = this.urlSerializer.parse(url);
  5239. }
  5240. catch (e) {
  5241. urlTree = this.malformedUriErrorHandler(e, this.urlSerializer, url);
  5242. }
  5243. return urlTree;
  5244. }
  5245. isActive(url, matchOptions) {
  5246. let options;
  5247. if (matchOptions === true) {
  5248. options = { ...exactMatchOptions };
  5249. }
  5250. else if (matchOptions === false) {
  5251. options = { ...subsetMatchOptions };
  5252. }
  5253. else {
  5254. options = matchOptions;
  5255. }
  5256. if (isUrlTree(url)) {
  5257. return containsTree(this.currentUrlTree, url, options);
  5258. }
  5259. const urlTree = this.parseUrl(url);
  5260. return containsTree(this.currentUrlTree, urlTree, options);
  5261. }
  5262. removeEmptyProps(params) {
  5263. return Object.keys(params).reduce((result, key) => {
  5264. const value = params[key];
  5265. if (value !== null && value !== undefined) {
  5266. result[key] = value;
  5267. }
  5268. return result;
  5269. }, {});
  5270. }
  5271. /** @internal */
  5272. scheduleNavigation(rawUrl, source, restoredState, extras, priorPromise) {
  5273. if (this.disposed) {
  5274. return Promise.resolve(false);
  5275. }
  5276. let resolve;
  5277. let reject;
  5278. let promise;
  5279. if (priorPromise) {
  5280. resolve = priorPromise.resolve;
  5281. reject = priorPromise.reject;
  5282. promise = priorPromise.promise;
  5283. }
  5284. else {
  5285. promise = new Promise((res, rej) => {
  5286. resolve = res;
  5287. reject = rej;
  5288. });
  5289. }
  5290. // Indicate that the navigation is happening.
  5291. const taskId = this.pendingTasks.add();
  5292. afterNextNavigation(this, () => {
  5293. // Remove pending task in a microtask to allow for cancelled
  5294. // initial navigations and redirects within the same task.
  5295. Promise.resolve().then(() => this.pendingTasks.remove(taskId));
  5296. });
  5297. this.navigationTransitions.handleNavigationRequest({
  5298. source,
  5299. restoredState,
  5300. currentUrlTree: this.currentUrlTree,
  5301. currentRawUrl: this.currentUrlTree,
  5302. rawUrl,
  5303. extras,
  5304. resolve,
  5305. reject,
  5306. promise,
  5307. currentSnapshot: this.routerState.snapshot,
  5308. currentRouterState: this.routerState
  5309. });
  5310. // Make sure that the error is propagated even though `processNavigations` catch
  5311. // handler does not rethrow
  5312. return promise.catch((e) => {
  5313. return Promise.reject(e);
  5314. });
  5315. }
  5316. /** @internal */
  5317. setBrowserUrl(url, transition) {
  5318. const path = this.urlSerializer.serialize(url);
  5319. if (this.location.isCurrentPathEqualTo(path) || !!transition.extras.replaceUrl) {
  5320. // replacements do not update the target page
  5321. const currentBrowserPageId = this.browserPageId;
  5322. const state = {
  5323. ...transition.extras.state,
  5324. ...this.generateNgRouterState(transition.id, currentBrowserPageId)
  5325. };
  5326. this.location.replaceState(path, '', state);
  5327. }
  5328. else {
  5329. const state = {
  5330. ...transition.extras.state,
  5331. ...this.generateNgRouterState(transition.id, (this.browserPageId ?? 0) + 1)
  5332. };
  5333. this.location.go(path, '', state);
  5334. }
  5335. }
  5336. /**
  5337. * Performs the necessary rollback action to restore the browser URL to the
  5338. * state before the transition.
  5339. * @internal
  5340. */
  5341. restoreHistory(transition, restoringFromCaughtError = false) {
  5342. if (this.canceledNavigationResolution === 'computed') {
  5343. const currentBrowserPageId = this.browserPageId ?? this.currentPageId;
  5344. const targetPagePosition = this.currentPageId - currentBrowserPageId;
  5345. if (targetPagePosition !== 0) {
  5346. this.location.historyGo(targetPagePosition);
  5347. }
  5348. else if (this.currentUrlTree === this.getCurrentNavigation()?.finalUrl &&
  5349. targetPagePosition === 0) {
  5350. // We got to the activation stage (where currentUrlTree is set to the navigation's
  5351. // finalUrl), but we weren't moving anywhere in history (skipLocationChange or replaceUrl).
  5352. // We still need to reset the router state back to what it was when the navigation started.
  5353. this.resetState(transition);
  5354. // TODO(atscott): resetting the `browserUrlTree` should really be done in `resetState`.
  5355. // Investigate if this can be done by running TGP.
  5356. this.browserUrlTree = transition.currentUrlTree;
  5357. this.resetUrlToCurrentUrlTree();
  5358. }
  5359. else {
  5360. // The browser URL and router state was not updated before the navigation cancelled so
  5361. // there's no restoration needed.
  5362. }
  5363. }
  5364. else if (this.canceledNavigationResolution === 'replace') {
  5365. // TODO(atscott): It seems like we should _always_ reset the state here. It would be a no-op
  5366. // for `deferred` navigations that haven't change the internal state yet because guards
  5367. // reject. For 'eager' navigations, it seems like we also really should reset the state
  5368. // because the navigation was cancelled. Investigate if this can be done by running TGP.
  5369. if (restoringFromCaughtError) {
  5370. this.resetState(transition);
  5371. }
  5372. this.resetUrlToCurrentUrlTree();
  5373. }
  5374. }
  5375. resetState(t) {
  5376. this.routerState = t.currentRouterState;
  5377. this.currentUrlTree = t.currentUrlTree;
  5378. // Note here that we use the urlHandlingStrategy to get the reset `rawUrlTree` because it may be
  5379. // configured to handle only part of the navigation URL. This means we would only want to reset
  5380. // the part of the navigation handled by the Angular router rather than the whole URL. In
  5381. // addition, the URLHandlingStrategy may be configured to specifically preserve parts of the URL
  5382. // when merging, such as the query params so they are not lost on a refresh.
  5383. this.rawUrlTree = this.urlHandlingStrategy.merge(this.currentUrlTree, t.rawUrl);
  5384. }
  5385. resetUrlToCurrentUrlTree() {
  5386. this.location.replaceState(this.urlSerializer.serialize(this.rawUrlTree), '', this.generateNgRouterState(this.lastSuccessfulId, this.currentPageId));
  5387. }
  5388. generateNgRouterState(navigationId, routerPageId) {
  5389. if (this.canceledNavigationResolution === 'computed') {
  5390. return { navigationId, ɵrouterPageId: routerPageId };
  5391. }
  5392. return { navigationId };
  5393. }
  5394. static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "16.0.4", ngImport: i0, type: Router, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
  5395. static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "16.0.4", ngImport: i0, type: Router, providedIn: 'root' }); }
  5396. }
  5397. i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "16.0.4", ngImport: i0, type: Router, decorators: [{
  5398. type: Injectable,
  5399. args: [{ providedIn: 'root' }]
  5400. }], ctorParameters: function () { return []; } });
  5401. function validateCommands(commands) {
  5402. for (let i = 0; i < commands.length; i++) {
  5403. const cmd = commands[i];
  5404. if (cmd == null) {
  5405. throw new ɵRuntimeError(4008 /* RuntimeErrorCode.NULLISH_COMMAND */, (typeof ngDevMode === 'undefined' || ngDevMode) &&
  5406. `The requested path contains ${cmd} segment at index ${i}`);
  5407. }
  5408. }
  5409. }
  5410. /**
  5411. * @description
  5412. *
  5413. * When applied to an element in a template, makes that element a link
  5414. * that initiates navigation to a route. Navigation opens one or more routed components
  5415. * in one or more `<router-outlet>` locations on the page.
  5416. *
  5417. * Given a route configuration `[{ path: 'user/:name', component: UserCmp }]`,
  5418. * the following creates a static link to the route:
  5419. * `<a routerLink="/user/bob">link to user component</a>`
  5420. *
  5421. * You can use dynamic values to generate the link.
  5422. * For a dynamic link, pass an array of path segments,
  5423. * followed by the params for each segment.
  5424. * For example, `['/team', teamId, 'user', userName, {details: true}]`
  5425. * generates a link to `/team/11/user/bob;details=true`.
  5426. *
  5427. * Multiple static segments can be merged into one term and combined with dynamic segments.
  5428. * For example, `['/team/11/user', userName, {details: true}]`
  5429. *
  5430. * The input that you provide to the link is treated as a delta to the current URL.
  5431. * For instance, suppose the current URL is `/user/(box//aux:team)`.
  5432. * The link `<a [routerLink]="['/user/jim']">Jim</a>` creates the URL
  5433. * `/user/(jim//aux:team)`.
  5434. * See {@link Router#createUrlTree createUrlTree} for more information.
  5435. *
  5436. * @usageNotes
  5437. *
  5438. * You can use absolute or relative paths in a link, set query parameters,
  5439. * control how parameters are handled, and keep a history of navigation states.
  5440. *
  5441. * ### Relative link paths
  5442. *
  5443. * The first segment name can be prepended with `/`, `./`, or `../`.
  5444. * * If the first segment begins with `/`, the router looks up the route from the root of the
  5445. * app.
  5446. * * If the first segment begins with `./`, or doesn't begin with a slash, the router
  5447. * looks in the children of the current activated route.
  5448. * * If the first segment begins with `../`, the router goes up one level in the route tree.
  5449. *
  5450. * ### Setting and handling query params and fragments
  5451. *
  5452. * The following link adds a query parameter and a fragment to the generated URL:
  5453. *
  5454. * ```
  5455. * <a [routerLink]="['/user/bob']" [queryParams]="{debug: true}" fragment="education">
  5456. * link to user component
  5457. * </a>
  5458. * ```
  5459. * By default, the directive constructs the new URL using the given query parameters.
  5460. * The example generates the link: `/user/bob?debug=true#education`.
  5461. *
  5462. * You can instruct the directive to handle query parameters differently
  5463. * by specifying the `queryParamsHandling` option in the link.
  5464. * Allowed values are:
  5465. *
  5466. * - `'merge'`: Merge the given `queryParams` into the current query params.
  5467. * - `'preserve'`: Preserve the current query params.
  5468. *
  5469. * For example:
  5470. *
  5471. * ```
  5472. * <a [routerLink]="['/user/bob']" [queryParams]="{debug: true}" queryParamsHandling="merge">
  5473. * link to user component
  5474. * </a>
  5475. * ```
  5476. *
  5477. * See {@link UrlCreationOptions.queryParamsHandling UrlCreationOptions#queryParamsHandling}.
  5478. *
  5479. * ### Preserving navigation history
  5480. *
  5481. * You can provide a `state` value to be persisted to the browser's
  5482. * [`History.state` property](https://developer.mozilla.org/en-US/docs/Web/API/History#Properties).
  5483. * For example:
  5484. *
  5485. * ```
  5486. * <a [routerLink]="['/user/bob']" [state]="{tracingId: 123}">
  5487. * link to user component
  5488. * </a>
  5489. * ```
  5490. *
  5491. * Use {@link Router.getCurrentNavigation() Router#getCurrentNavigation} to retrieve a saved
  5492. * navigation-state value. For example, to capture the `tracingId` during the `NavigationStart`
  5493. * event:
  5494. *
  5495. * ```
  5496. * // Get NavigationStart events
  5497. * router.events.pipe(filter(e => e instanceof NavigationStart)).subscribe(e => {
  5498. * const navigation = router.getCurrentNavigation();
  5499. * tracingService.trace({id: navigation.extras.state.tracingId});
  5500. * });
  5501. * ```
  5502. *
  5503. * @ngModule RouterModule
  5504. *
  5505. * @publicApi
  5506. */
  5507. class RouterLink {
  5508. constructor(router, route, tabIndexAttribute, renderer, el, locationStrategy) {
  5509. this.router = router;
  5510. this.route = route;
  5511. this.tabIndexAttribute = tabIndexAttribute;
  5512. this.renderer = renderer;
  5513. this.el = el;
  5514. this.locationStrategy = locationStrategy;
  5515. this._preserveFragment = false;
  5516. this._skipLocationChange = false;
  5517. this._replaceUrl = false;
  5518. /**
  5519. * Represents an `href` attribute value applied to a host element,
  5520. * when a host element is `<a>`. For other tags, the value is `null`.
  5521. */
  5522. this.href = null;
  5523. this.commands = null;
  5524. /** @internal */
  5525. this.onChanges = new Subject();
  5526. const tagName = el.nativeElement.tagName?.toLowerCase();
  5527. this.isAnchorElement = tagName === 'a' || tagName === 'area';
  5528. if (this.isAnchorElement) {
  5529. this.subscription = router.events.subscribe((s) => {
  5530. if (s instanceof NavigationEnd) {
  5531. this.updateHref();
  5532. }
  5533. });
  5534. }
  5535. else {
  5536. this.setTabIndexIfNotOnNativeEl('0');
  5537. }
  5538. }
  5539. /**
  5540. * Passed to {@link Router#createUrlTree Router#createUrlTree} as part of the
  5541. * `UrlCreationOptions`.
  5542. * @see {@link UrlCreationOptions#preserveFragment UrlCreationOptions#preserveFragment}
  5543. * @see {@link Router#createUrlTree Router#createUrlTree}
  5544. */
  5545. set preserveFragment(preserveFragment) {
  5546. this._preserveFragment = ɵcoerceToBoolean(preserveFragment);
  5547. }
  5548. get preserveFragment() {
  5549. return this._preserveFragment;
  5550. }
  5551. /**
  5552. * Passed to {@link Router#navigateByUrl Router#navigateByUrl} as part of the
  5553. * `NavigationBehaviorOptions`.
  5554. * @see {@link NavigationBehaviorOptions#skipLocationChange NavigationBehaviorOptions#skipLocationChange}
  5555. * @see {@link Router#navigateByUrl Router#navigateByUrl}
  5556. */
  5557. set skipLocationChange(skipLocationChange) {
  5558. this._skipLocationChange = ɵcoerceToBoolean(skipLocationChange);
  5559. }
  5560. get skipLocationChange() {
  5561. return this._skipLocationChange;
  5562. }
  5563. /**
  5564. * Passed to {@link Router#navigateByUrl Router#navigateByUrl} as part of the
  5565. * `NavigationBehaviorOptions`.
  5566. * @see {@link NavigationBehaviorOptions#replaceUrl NavigationBehaviorOptions#replaceUrl}
  5567. * @see {@link Router#navigateByUrl Router#navigateByUrl}
  5568. */
  5569. set replaceUrl(replaceUrl) {
  5570. this._replaceUrl = ɵcoerceToBoolean(replaceUrl);
  5571. }
  5572. get replaceUrl() {
  5573. return this._replaceUrl;
  5574. }
  5575. /**
  5576. * Modifies the tab index if there was not a tabindex attribute on the element during
  5577. * instantiation.
  5578. */
  5579. setTabIndexIfNotOnNativeEl(newTabIndex) {
  5580. if (this.tabIndexAttribute != null /* both `null` and `undefined` */ || this.isAnchorElement) {
  5581. return;
  5582. }
  5583. this.applyAttributeValue('tabindex', newTabIndex);
  5584. }
  5585. /** @nodoc */
  5586. ngOnChanges(changes) {
  5587. if (this.isAnchorElement) {
  5588. this.updateHref();
  5589. }
  5590. // This is subscribed to by `RouterLinkActive` so that it knows to update when there are changes
  5591. // to the RouterLinks it's tracking.
  5592. this.onChanges.next(this);
  5593. }
  5594. /**
  5595. * Commands to pass to {@link Router#createUrlTree Router#createUrlTree}.
  5596. * - **array**: commands to pass to {@link Router#createUrlTree Router#createUrlTree}.
  5597. * - **string**: shorthand for array of commands with just the string, i.e. `['/route']`
  5598. * - **null|undefined**: effectively disables the `routerLink`
  5599. * @see {@link Router#createUrlTree Router#createUrlTree}
  5600. */
  5601. set routerLink(commands) {
  5602. if (commands != null) {
  5603. this.commands = Array.isArray(commands) ? commands : [commands];
  5604. this.setTabIndexIfNotOnNativeEl('0');
  5605. }
  5606. else {
  5607. this.commands = null;
  5608. this.setTabIndexIfNotOnNativeEl(null);
  5609. }
  5610. }
  5611. /** @nodoc */
  5612. onClick(button, ctrlKey, shiftKey, altKey, metaKey) {
  5613. if (this.urlTree === null) {
  5614. return true;
  5615. }
  5616. if (this.isAnchorElement) {
  5617. if (button !== 0 || ctrlKey || shiftKey || altKey || metaKey) {
  5618. return true;
  5619. }
  5620. if (typeof this.target === 'string' && this.target != '_self') {
  5621. return true;
  5622. }
  5623. }
  5624. const extras = {
  5625. skipLocationChange: this.skipLocationChange,
  5626. replaceUrl: this.replaceUrl,
  5627. state: this.state,
  5628. };
  5629. this.router.navigateByUrl(this.urlTree, extras);
  5630. // Return `false` for `<a>` elements to prevent default action
  5631. // and cancel the native behavior, since the navigation is handled
  5632. // by the Router.
  5633. return !this.isAnchorElement;
  5634. }
  5635. /** @nodoc */
  5636. ngOnDestroy() {
  5637. this.subscription?.unsubscribe();
  5638. }
  5639. updateHref() {
  5640. this.href = this.urlTree !== null && this.locationStrategy ?
  5641. this.locationStrategy?.prepareExternalUrl(this.router.serializeUrl(this.urlTree)) :
  5642. null;
  5643. const sanitizedValue = this.href === null ?
  5644. null :
  5645. // This class represents a directive that can be added to both `<a>` elements,
  5646. // as well as other elements. As a result, we can't define security context at
  5647. // compile time. So the security context is deferred to runtime.
  5648. // The `ɵɵsanitizeUrlOrResourceUrl` selects the necessary sanitizer function
  5649. // based on the tag and property names. The logic mimics the one from
  5650. // `packages/compiler/src/schema/dom_security_schema.ts`, which is used at compile time.
  5651. //
  5652. // Note: we should investigate whether we can switch to using `@HostBinding('attr.href')`
  5653. // instead of applying a value via a renderer, after a final merge of the
  5654. // `RouterLinkWithHref` directive.
  5655. ɵɵsanitizeUrlOrResourceUrl(this.href, this.el.nativeElement.tagName.toLowerCase(), 'href');
  5656. this.applyAttributeValue('href', sanitizedValue);
  5657. }
  5658. applyAttributeValue(attrName, attrValue) {
  5659. const renderer = this.renderer;
  5660. const nativeElement = this.el.nativeElement;
  5661. if (attrValue !== null) {
  5662. renderer.setAttribute(nativeElement, attrName, attrValue);
  5663. }
  5664. else {
  5665. renderer.removeAttribute(nativeElement, attrName);
  5666. }
  5667. }
  5668. get urlTree() {
  5669. if (this.commands === null) {
  5670. return null;
  5671. }
  5672. return this.router.createUrlTree(this.commands, {
  5673. // If the `relativeTo` input is not defined, we want to use `this.route` by default.
  5674. // Otherwise, we should use the value provided by the user in the input.
  5675. relativeTo: this.relativeTo !== undefined ? this.relativeTo : this.route,
  5676. queryParams: this.queryParams,
  5677. fragment: this.fragment,
  5678. queryParamsHandling: this.queryParamsHandling,
  5679. preserveFragment: this.preserveFragment,
  5680. });
  5681. }
  5682. static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "16.0.4", ngImport: i0, type: RouterLink, deps: [{ token: Router }, { token: ActivatedRoute }, { token: 'tabindex', attribute: true }, { token: i0.Renderer2 }, { token: i0.ElementRef }, { token: i3.LocationStrategy }], target: i0.ɵɵFactoryTarget.Directive }); }
  5683. static { this.ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "14.0.0", version: "16.0.4", type: RouterLink, isStandalone: true, selector: "[routerLink]", inputs: { target: "target", queryParams: "queryParams", fragment: "fragment", queryParamsHandling: "queryParamsHandling", state: "state", relativeTo: "relativeTo", preserveFragment: "preserveFragment", skipLocationChange: "skipLocationChange", replaceUrl: "replaceUrl", routerLink: "routerLink" }, host: { listeners: { "click": "onClick($event.button,$event.ctrlKey,$event.shiftKey,$event.altKey,$event.metaKey)" }, properties: { "attr.target": "this.target" } }, usesOnChanges: true, ngImport: i0 }); }
  5684. }
  5685. i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "16.0.4", ngImport: i0, type: RouterLink, decorators: [{
  5686. type: Directive,
  5687. args: [{
  5688. selector: '[routerLink]',
  5689. standalone: true,
  5690. }]
  5691. }], ctorParameters: function () { return [{ type: Router }, { type: ActivatedRoute }, { type: undefined, decorators: [{
  5692. type: Attribute,
  5693. args: ['tabindex']
  5694. }] }, { type: i0.Renderer2 }, { type: i0.ElementRef }, { type: i3.LocationStrategy }]; }, propDecorators: { target: [{
  5695. type: HostBinding,
  5696. args: ['attr.target']
  5697. }, {
  5698. type: Input
  5699. }], queryParams: [{
  5700. type: Input
  5701. }], fragment: [{
  5702. type: Input
  5703. }], queryParamsHandling: [{
  5704. type: Input
  5705. }], state: [{
  5706. type: Input
  5707. }], relativeTo: [{
  5708. type: Input
  5709. }], preserveFragment: [{
  5710. type: Input
  5711. }], skipLocationChange: [{
  5712. type: Input
  5713. }], replaceUrl: [{
  5714. type: Input
  5715. }], routerLink: [{
  5716. type: Input
  5717. }], onClick: [{
  5718. type: HostListener,
  5719. args: ['click',
  5720. ['$event.button', '$event.ctrlKey', '$event.shiftKey', '$event.altKey', '$event.metaKey']]
  5721. }] } });
  5722. /**
  5723. *
  5724. * @description
  5725. *
  5726. * Tracks whether the linked route of an element is currently active, and allows you
  5727. * to specify one or more CSS classes to add to the element when the linked route
  5728. * is active.
  5729. *
  5730. * Use this directive to create a visual distinction for elements associated with an active route.
  5731. * For example, the following code highlights the word "Bob" when the router
  5732. * activates the associated route:
  5733. *
  5734. * ```
  5735. * <a routerLink="/user/bob" routerLinkActive="active-link">Bob</a>
  5736. * ```
  5737. *
  5738. * Whenever the URL is either '/user' or '/user/bob', the "active-link" class is
  5739. * added to the anchor tag. If the URL changes, the class is removed.
  5740. *
  5741. * You can set more than one class using a space-separated string or an array.
  5742. * For example:
  5743. *
  5744. * ```
  5745. * <a routerLink="/user/bob" routerLinkActive="class1 class2">Bob</a>
  5746. * <a routerLink="/user/bob" [routerLinkActive]="['class1', 'class2']">Bob</a>
  5747. * ```
  5748. *
  5749. * To add the classes only when the URL matches the link exactly, add the option `exact: true`:
  5750. *
  5751. * ```
  5752. * <a routerLink="/user/bob" routerLinkActive="active-link" [routerLinkActiveOptions]="{exact:
  5753. * true}">Bob</a>
  5754. * ```
  5755. *
  5756. * To directly check the `isActive` status of the link, assign the `RouterLinkActive`
  5757. * instance to a template variable.
  5758. * For example, the following checks the status without assigning any CSS classes:
  5759. *
  5760. * ```
  5761. * <a routerLink="/user/bob" routerLinkActive #rla="routerLinkActive">
  5762. * Bob {{ rla.isActive ? '(already open)' : ''}}
  5763. * </a>
  5764. * ```
  5765. *
  5766. * You can apply the `RouterLinkActive` directive to an ancestor of linked elements.
  5767. * For example, the following sets the active-link class on the `<div>` parent tag
  5768. * when the URL is either '/user/jim' or '/user/bob'.
  5769. *
  5770. * ```
  5771. * <div routerLinkActive="active-link" [routerLinkActiveOptions]="{exact: true}">
  5772. * <a routerLink="/user/jim">Jim</a>
  5773. * <a routerLink="/user/bob">Bob</a>
  5774. * </div>
  5775. * ```
  5776. *
  5777. * The `RouterLinkActive` directive can also be used to set the aria-current attribute
  5778. * to provide an alternative distinction for active elements to visually impaired users.
  5779. *
  5780. * For example, the following code adds the 'active' class to the Home Page link when it is
  5781. * indeed active and in such case also sets its aria-current attribute to 'page':
  5782. *
  5783. * ```
  5784. * <a routerLink="/" routerLinkActive="active" ariaCurrentWhenActive="page">Home Page</a>
  5785. * ```
  5786. *
  5787. * @ngModule RouterModule
  5788. *
  5789. * @publicApi
  5790. */
  5791. class RouterLinkActive {
  5792. get isActive() {
  5793. return this._isActive;
  5794. }
  5795. constructor(router, element, renderer, cdr, link) {
  5796. this.router = router;
  5797. this.element = element;
  5798. this.renderer = renderer;
  5799. this.cdr = cdr;
  5800. this.link = link;
  5801. this.classes = [];
  5802. this._isActive = false;
  5803. /**
  5804. * Options to configure how to determine if the router link is active.
  5805. *
  5806. * These options are passed to the `Router.isActive()` function.
  5807. *
  5808. * @see Router.isActive
  5809. */
  5810. this.routerLinkActiveOptions = { exact: false };
  5811. /**
  5812. *
  5813. * You can use the output `isActiveChange` to get notified each time the link becomes
  5814. * active or inactive.
  5815. *
  5816. * Emits:
  5817. * true -> Route is active
  5818. * false -> Route is inactive
  5819. *
  5820. * ```
  5821. * <a
  5822. * routerLink="/user/bob"
  5823. * routerLinkActive="active-link"
  5824. * (isActiveChange)="this.onRouterLinkActive($event)">Bob</a>
  5825. * ```
  5826. */
  5827. this.isActiveChange = new EventEmitter();
  5828. this.routerEventsSubscription = router.events.subscribe((s) => {
  5829. if (s instanceof NavigationEnd) {
  5830. this.update();
  5831. }
  5832. });
  5833. }
  5834. /** @nodoc */
  5835. ngAfterContentInit() {
  5836. // `of(null)` is used to force subscribe body to execute once immediately (like `startWith`).
  5837. of(this.links.changes, of(null)).pipe(mergeAll()).subscribe(_ => {
  5838. this.update();
  5839. this.subscribeToEachLinkOnChanges();
  5840. });
  5841. }
  5842. subscribeToEachLinkOnChanges() {
  5843. this.linkInputChangesSubscription?.unsubscribe();
  5844. const allLinkChanges = [...this.links.toArray(), this.link]
  5845. .filter((link) => !!link)
  5846. .map(link => link.onChanges);
  5847. this.linkInputChangesSubscription = from(allLinkChanges).pipe(mergeAll()).subscribe(link => {
  5848. if (this._isActive !== this.isLinkActive(this.router)(link)) {
  5849. this.update();
  5850. }
  5851. });
  5852. }
  5853. set routerLinkActive(data) {
  5854. const classes = Array.isArray(data) ? data : data.split(' ');
  5855. this.classes = classes.filter(c => !!c);
  5856. }
  5857. /** @nodoc */
  5858. ngOnChanges(changes) {
  5859. this.update();
  5860. }
  5861. /** @nodoc */
  5862. ngOnDestroy() {
  5863. this.routerEventsSubscription.unsubscribe();
  5864. this.linkInputChangesSubscription?.unsubscribe();
  5865. }
  5866. update() {
  5867. if (!this.links || !this.router.navigated)
  5868. return;
  5869. Promise.resolve().then(() => {
  5870. const hasActiveLinks = this.hasActiveLinks();
  5871. if (this._isActive !== hasActiveLinks) {
  5872. this._isActive = hasActiveLinks;
  5873. this.cdr.markForCheck();
  5874. this.classes.forEach((c) => {
  5875. if (hasActiveLinks) {
  5876. this.renderer.addClass(this.element.nativeElement, c);
  5877. }
  5878. else {
  5879. this.renderer.removeClass(this.element.nativeElement, c);
  5880. }
  5881. });
  5882. if (hasActiveLinks && this.ariaCurrentWhenActive !== undefined) {
  5883. this.renderer.setAttribute(this.element.nativeElement, 'aria-current', this.ariaCurrentWhenActive.toString());
  5884. }
  5885. else {
  5886. this.renderer.removeAttribute(this.element.nativeElement, 'aria-current');
  5887. }
  5888. // Emit on isActiveChange after classes are updated
  5889. this.isActiveChange.emit(hasActiveLinks);
  5890. }
  5891. });
  5892. }
  5893. isLinkActive(router) {
  5894. const options = isActiveMatchOptions(this.routerLinkActiveOptions) ?
  5895. this.routerLinkActiveOptions :
  5896. // While the types should disallow `undefined` here, it's possible without strict inputs
  5897. (this.routerLinkActiveOptions.exact || false);
  5898. return (link) => link.urlTree ? router.isActive(link.urlTree, options) : false;
  5899. }
  5900. hasActiveLinks() {
  5901. const isActiveCheckFn = this.isLinkActive(this.router);
  5902. return this.link && isActiveCheckFn(this.link) || this.links.some(isActiveCheckFn);
  5903. }
  5904. static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "16.0.4", ngImport: i0, type: RouterLinkActive, deps: [{ token: Router }, { token: i0.ElementRef }, { token: i0.Renderer2 }, { token: i0.ChangeDetectorRef }, { token: RouterLink, optional: true }], target: i0.ɵɵFactoryTarget.Directive }); }
  5905. static { this.ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "14.0.0", version: "16.0.4", type: RouterLinkActive, isStandalone: true, selector: "[routerLinkActive]", inputs: { routerLinkActiveOptions: "routerLinkActiveOptions", ariaCurrentWhenActive: "ariaCurrentWhenActive", routerLinkActive: "routerLinkActive" }, outputs: { isActiveChange: "isActiveChange" }, queries: [{ propertyName: "links", predicate: RouterLink, descendants: true }], exportAs: ["routerLinkActive"], usesOnChanges: true, ngImport: i0 }); }
  5906. }
  5907. i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "16.0.4", ngImport: i0, type: RouterLinkActive, decorators: [{
  5908. type: Directive,
  5909. args: [{
  5910. selector: '[routerLinkActive]',
  5911. exportAs: 'routerLinkActive',
  5912. standalone: true,
  5913. }]
  5914. }], ctorParameters: function () { return [{ type: Router }, { type: i0.ElementRef }, { type: i0.Renderer2 }, { type: i0.ChangeDetectorRef }, { type: RouterLink, decorators: [{
  5915. type: Optional
  5916. }] }]; }, propDecorators: { links: [{
  5917. type: ContentChildren,
  5918. args: [RouterLink, { descendants: true }]
  5919. }], routerLinkActiveOptions: [{
  5920. type: Input
  5921. }], ariaCurrentWhenActive: [{
  5922. type: Input
  5923. }], isActiveChange: [{
  5924. type: Output
  5925. }], routerLinkActive: [{
  5926. type: Input
  5927. }] } });
  5928. /**
  5929. * Use instead of `'paths' in options` to be compatible with property renaming
  5930. */
  5931. function isActiveMatchOptions(options) {
  5932. return !!options.paths;
  5933. }
  5934. /**
  5935. * @description
  5936. *
  5937. * Provides a preloading strategy.
  5938. *
  5939. * @publicApi
  5940. */
  5941. class PreloadingStrategy {
  5942. }
  5943. /**
  5944. * @description
  5945. *
  5946. * Provides a preloading strategy that preloads all modules as quickly as possible.
  5947. *
  5948. * ```
  5949. * RouterModule.forRoot(ROUTES, {preloadingStrategy: PreloadAllModules})
  5950. * ```
  5951. *
  5952. * @publicApi
  5953. */
  5954. class PreloadAllModules {
  5955. preload(route, fn) {
  5956. return fn().pipe(catchError(() => of(null)));
  5957. }
  5958. static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "16.0.4", ngImport: i0, type: PreloadAllModules, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
  5959. static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "16.0.4", ngImport: i0, type: PreloadAllModules, providedIn: 'root' }); }
  5960. }
  5961. i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "16.0.4", ngImport: i0, type: PreloadAllModules, decorators: [{
  5962. type: Injectable,
  5963. args: [{ providedIn: 'root' }]
  5964. }] });
  5965. /**
  5966. * @description
  5967. *
  5968. * Provides a preloading strategy that does not preload any modules.
  5969. *
  5970. * This strategy is enabled by default.
  5971. *
  5972. * @publicApi
  5973. */
  5974. class NoPreloading {
  5975. preload(route, fn) {
  5976. return of(null);
  5977. }
  5978. static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "16.0.4", ngImport: i0, type: NoPreloading, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
  5979. static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "16.0.4", ngImport: i0, type: NoPreloading, providedIn: 'root' }); }
  5980. }
  5981. i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "16.0.4", ngImport: i0, type: NoPreloading, decorators: [{
  5982. type: Injectable,
  5983. args: [{ providedIn: 'root' }]
  5984. }] });
  5985. /**
  5986. * The preloader optimistically loads all router configurations to
  5987. * make navigations into lazily-loaded sections of the application faster.
  5988. *
  5989. * The preloader runs in the background. When the router bootstraps, the preloader
  5990. * starts listening to all navigation events. After every such event, the preloader
  5991. * will check if any configurations can be loaded lazily.
  5992. *
  5993. * If a route is protected by `canLoad` guards, the preloaded will not load it.
  5994. *
  5995. * @publicApi
  5996. */
  5997. class RouterPreloader {
  5998. constructor(router, compiler, injector, preloadingStrategy, loader) {
  5999. this.router = router;
  6000. this.injector = injector;
  6001. this.preloadingStrategy = preloadingStrategy;
  6002. this.loader = loader;
  6003. }
  6004. setUpPreloading() {
  6005. this.subscription =
  6006. this.router.events
  6007. .pipe(filter((e) => e instanceof NavigationEnd), concatMap(() => this.preload()))
  6008. .subscribe(() => { });
  6009. }
  6010. preload() {
  6011. return this.processRoutes(this.injector, this.router.config);
  6012. }
  6013. /** @nodoc */
  6014. ngOnDestroy() {
  6015. if (this.subscription) {
  6016. this.subscription.unsubscribe();
  6017. }
  6018. }
  6019. processRoutes(injector, routes) {
  6020. const res = [];
  6021. for (const route of routes) {
  6022. if (route.providers && !route._injector) {
  6023. route._injector =
  6024. createEnvironmentInjector(route.providers, injector, `Route: ${route.path}`);
  6025. }
  6026. const injectorForCurrentRoute = route._injector ?? injector;
  6027. const injectorForChildren = route._loadedInjector ?? injectorForCurrentRoute;
  6028. // Note that `canLoad` is only checked as a condition that prevents `loadChildren` and not
  6029. // `loadComponent`. `canLoad` guards only block loading of child routes by design. This
  6030. // happens as a consequence of needing to descend into children for route matching immediately
  6031. // while component loading is deferred until route activation. Because `canLoad` guards can
  6032. // have side effects, we cannot execute them here so we instead skip preloading altogether
  6033. // when present. Lastly, it remains to be decided whether `canLoad` should behave this way
  6034. // at all. Code splitting and lazy loading is separate from client-side authorization checks
  6035. // and should not be used as a security measure to prevent loading of code.
  6036. if ((route.loadChildren && !route._loadedRoutes && route.canLoad === undefined) ||
  6037. (route.loadComponent && !route._loadedComponent)) {
  6038. res.push(this.preloadConfig(injectorForCurrentRoute, route));
  6039. }
  6040. if (route.children || route._loadedRoutes) {
  6041. res.push(this.processRoutes(injectorForChildren, (route.children ?? route._loadedRoutes)));
  6042. }
  6043. }
  6044. return from(res).pipe(mergeAll());
  6045. }
  6046. preloadConfig(injector, route) {
  6047. return this.preloadingStrategy.preload(route, () => {
  6048. let loadedChildren$;
  6049. if (route.loadChildren && route.canLoad === undefined) {
  6050. loadedChildren$ = this.loader.loadChildren(injector, route);
  6051. }
  6052. else {
  6053. loadedChildren$ = of(null);
  6054. }
  6055. const recursiveLoadChildren$ = loadedChildren$.pipe(mergeMap((config) => {
  6056. if (config === null) {
  6057. return of(void 0);
  6058. }
  6059. route._loadedRoutes = config.routes;
  6060. route._loadedInjector = config.injector;
  6061. // If the loaded config was a module, use that as the module/module injector going
  6062. // forward. Otherwise, continue using the current module/module injector.
  6063. return this.processRoutes(config.injector ?? injector, config.routes);
  6064. }));
  6065. if (route.loadComponent && !route._loadedComponent) {
  6066. const loadComponent$ = this.loader.loadComponent(route);
  6067. return from([recursiveLoadChildren$, loadComponent$]).pipe(mergeAll());
  6068. }
  6069. else {
  6070. return recursiveLoadChildren$;
  6071. }
  6072. });
  6073. }
  6074. static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "16.0.4", ngImport: i0, type: RouterPreloader, deps: [{ token: Router }, { token: i0.Compiler }, { token: i0.EnvironmentInjector }, { token: PreloadingStrategy }, { token: RouterConfigLoader }], target: i0.ɵɵFactoryTarget.Injectable }); }
  6075. static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "16.0.4", ngImport: i0, type: RouterPreloader, providedIn: 'root' }); }
  6076. }
  6077. i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "16.0.4", ngImport: i0, type: RouterPreloader, decorators: [{
  6078. type: Injectable,
  6079. args: [{ providedIn: 'root' }]
  6080. }], ctorParameters: function () { return [{ type: Router }, { type: i0.Compiler }, { type: i0.EnvironmentInjector }, { type: PreloadingStrategy }, { type: RouterConfigLoader }]; } });
  6081. const ROUTER_SCROLLER = new InjectionToken('');
  6082. class RouterScroller {
  6083. /** @nodoc */
  6084. constructor(urlSerializer, transitions, viewportScroller, zone, options = {}) {
  6085. this.urlSerializer = urlSerializer;
  6086. this.transitions = transitions;
  6087. this.viewportScroller = viewportScroller;
  6088. this.zone = zone;
  6089. this.options = options;
  6090. this.lastId = 0;
  6091. this.lastSource = 'imperative';
  6092. this.restoredId = 0;
  6093. this.store = {};
  6094. // Default both options to 'disabled'
  6095. options.scrollPositionRestoration = options.scrollPositionRestoration || 'disabled';
  6096. options.anchorScrolling = options.anchorScrolling || 'disabled';
  6097. }
  6098. init() {
  6099. // we want to disable the automatic scrolling because having two places
  6100. // responsible for scrolling results race conditions, especially given
  6101. // that browser don't implement this behavior consistently
  6102. if (this.options.scrollPositionRestoration !== 'disabled') {
  6103. this.viewportScroller.setHistoryScrollRestoration('manual');
  6104. }
  6105. this.routerEventsSubscription = this.createScrollEvents();
  6106. this.scrollEventsSubscription = this.consumeScrollEvents();
  6107. }
  6108. createScrollEvents() {
  6109. return this.transitions.events.subscribe(e => {
  6110. if (e instanceof NavigationStart) {
  6111. // store the scroll position of the current stable navigations.
  6112. this.store[this.lastId] = this.viewportScroller.getScrollPosition();
  6113. this.lastSource = e.navigationTrigger;
  6114. this.restoredId = e.restoredState ? e.restoredState.navigationId : 0;
  6115. }
  6116. else if (e instanceof NavigationEnd) {
  6117. this.lastId = e.id;
  6118. this.scheduleScrollEvent(e, this.urlSerializer.parse(e.urlAfterRedirects).fragment);
  6119. }
  6120. else if (e instanceof NavigationSkipped &&
  6121. e.code === 0 /* NavigationSkippedCode.IgnoredSameUrlNavigation */) {
  6122. this.lastSource = undefined;
  6123. this.restoredId = 0;
  6124. this.scheduleScrollEvent(e, this.urlSerializer.parse(e.url).fragment);
  6125. }
  6126. });
  6127. }
  6128. consumeScrollEvents() {
  6129. return this.transitions.events.subscribe(e => {
  6130. if (!(e instanceof Scroll))
  6131. return;
  6132. // a popstate event. The pop state event will always ignore anchor scrolling.
  6133. if (e.position) {
  6134. if (this.options.scrollPositionRestoration === 'top') {
  6135. this.viewportScroller.scrollToPosition([0, 0]);
  6136. }
  6137. else if (this.options.scrollPositionRestoration === 'enabled') {
  6138. this.viewportScroller.scrollToPosition(e.position);
  6139. }
  6140. // imperative navigation "forward"
  6141. }
  6142. else {
  6143. if (e.anchor && this.options.anchorScrolling === 'enabled') {
  6144. this.viewportScroller.scrollToAnchor(e.anchor);
  6145. }
  6146. else if (this.options.scrollPositionRestoration !== 'disabled') {
  6147. this.viewportScroller.scrollToPosition([0, 0]);
  6148. }
  6149. }
  6150. });
  6151. }
  6152. scheduleScrollEvent(routerEvent, anchor) {
  6153. this.zone.runOutsideAngular(() => {
  6154. // The scroll event needs to be delayed until after change detection. Otherwise, we may
  6155. // attempt to restore the scroll position before the router outlet has fully rendered the
  6156. // component by executing its update block of the template function.
  6157. setTimeout(() => {
  6158. this.zone.run(() => {
  6159. this.transitions.events.next(new Scroll(routerEvent, this.lastSource === 'popstate' ? this.store[this.restoredId] : null, anchor));
  6160. });
  6161. }, 0);
  6162. });
  6163. }
  6164. /** @nodoc */
  6165. ngOnDestroy() {
  6166. this.routerEventsSubscription?.unsubscribe();
  6167. this.scrollEventsSubscription?.unsubscribe();
  6168. }
  6169. static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "16.0.4", ngImport: i0, type: RouterScroller, deps: "invalid", target: i0.ɵɵFactoryTarget.Injectable }); }
  6170. static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "16.0.4", ngImport: i0, type: RouterScroller }); }
  6171. }
  6172. i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "16.0.4", ngImport: i0, type: RouterScroller, decorators: [{
  6173. type: Injectable
  6174. }], ctorParameters: function () { return [{ type: UrlSerializer }, { type: NavigationTransitions }, { type: i3.ViewportScroller }, { type: i0.NgZone }, { type: undefined }]; } });
  6175. /**
  6176. * Sets up providers necessary to enable `Router` functionality for the application.
  6177. * Allows to configure a set of routes as well as extra features that should be enabled.
  6178. *
  6179. * @usageNotes
  6180. *
  6181. * Basic example of how you can add a Router to your application:
  6182. * ```
  6183. * const appRoutes: Routes = [];
  6184. * bootstrapApplication(AppComponent, {
  6185. * providers: [provideRouter(appRoutes)]
  6186. * });
  6187. * ```
  6188. *
  6189. * You can also enable optional features in the Router by adding functions from the `RouterFeatures`
  6190. * type:
  6191. * ```
  6192. * const appRoutes: Routes = [];
  6193. * bootstrapApplication(AppComponent,
  6194. * {
  6195. * providers: [
  6196. * provideRouter(appRoutes,
  6197. * withDebugTracing(),
  6198. * withRouterConfig({paramsInheritanceStrategy: 'always'}))
  6199. * ]
  6200. * }
  6201. * );
  6202. * ```
  6203. *
  6204. * @see `RouterFeatures`
  6205. *
  6206. * @publicApi
  6207. * @param routes A set of `Route`s to use for the application routing table.
  6208. * @param features Optional features to configure additional router behaviors.
  6209. * @returns A set of providers to setup a Router.
  6210. */
  6211. function provideRouter(routes, ...features) {
  6212. return makeEnvironmentProviders([
  6213. { provide: ROUTES, multi: true, useValue: routes },
  6214. (typeof ngDevMode === 'undefined' || ngDevMode) ?
  6215. { provide: ROUTER_IS_PROVIDED, useValue: true } :
  6216. [],
  6217. { provide: ActivatedRoute, useFactory: rootRoute, deps: [Router] },
  6218. { provide: APP_BOOTSTRAP_LISTENER, multi: true, useFactory: getBootstrapListener },
  6219. features.map(feature => feature.ɵproviders),
  6220. ]);
  6221. }
  6222. function rootRoute(router) {
  6223. return router.routerState.root;
  6224. }
  6225. /**
  6226. * Helper function to create an object that represents a Router feature.
  6227. */
  6228. function routerFeature(kind, providers) {
  6229. return { ɵkind: kind, ɵproviders: providers };
  6230. }
  6231. /**
  6232. * An Injection token used to indicate whether `provideRouter` or `RouterModule.forRoot` was ever
  6233. * called.
  6234. */
  6235. const ROUTER_IS_PROVIDED = new InjectionToken('', { providedIn: 'root', factory: () => false });
  6236. const routerIsProvidedDevModeCheck = {
  6237. provide: ENVIRONMENT_INITIALIZER,
  6238. multi: true,
  6239. useFactory() {
  6240. return () => {
  6241. if (!inject(ROUTER_IS_PROVIDED)) {
  6242. console.warn('`provideRoutes` was called without `provideRouter` or `RouterModule.forRoot`. ' +
  6243. 'This is likely a mistake.');
  6244. }
  6245. };
  6246. }
  6247. };
  6248. /**
  6249. * Registers a [DI provider](guide/glossary#provider) for a set of routes.
  6250. * @param routes The route configuration to provide.
  6251. *
  6252. * @usageNotes
  6253. *
  6254. * ```
  6255. * @NgModule({
  6256. * providers: [provideRoutes(ROUTES)]
  6257. * })
  6258. * class LazyLoadedChildModule {}
  6259. * ```
  6260. *
  6261. * @deprecated If necessary, provide routes using the `ROUTES` `InjectionToken`.
  6262. * @see `ROUTES`
  6263. * @publicApi
  6264. */
  6265. function provideRoutes(routes) {
  6266. return [
  6267. { provide: ROUTES, multi: true, useValue: routes },
  6268. (typeof ngDevMode === 'undefined' || ngDevMode) ? routerIsProvidedDevModeCheck : [],
  6269. ];
  6270. }
  6271. /**
  6272. * Enables customizable scrolling behavior for router navigations.
  6273. *
  6274. * @usageNotes
  6275. *
  6276. * Basic example of how you can enable scrolling feature:
  6277. * ```
  6278. * const appRoutes: Routes = [];
  6279. * bootstrapApplication(AppComponent,
  6280. * {
  6281. * providers: [
  6282. * provideRouter(appRoutes, withInMemoryScrolling())
  6283. * ]
  6284. * }
  6285. * );
  6286. * ```
  6287. *
  6288. * @see `provideRouter`
  6289. * @see `ViewportScroller`
  6290. *
  6291. * @publicApi
  6292. * @param options Set of configuration parameters to customize scrolling behavior, see
  6293. * `InMemoryScrollingOptions` for additional information.
  6294. * @returns A set of providers for use with `provideRouter`.
  6295. */
  6296. function withInMemoryScrolling(options = {}) {
  6297. const providers = [{
  6298. provide: ROUTER_SCROLLER,
  6299. useFactory: () => {
  6300. const viewportScroller = inject(ViewportScroller);
  6301. const zone = inject(NgZone);
  6302. const transitions = inject(NavigationTransitions);
  6303. const urlSerializer = inject(UrlSerializer);
  6304. return new RouterScroller(urlSerializer, transitions, viewportScroller, zone, options);
  6305. },
  6306. }];
  6307. return routerFeature(4 /* RouterFeatureKind.InMemoryScrollingFeature */, providers);
  6308. }
  6309. function getBootstrapListener() {
  6310. const injector = inject(Injector);
  6311. return (bootstrappedComponentRef) => {
  6312. const ref = injector.get(ApplicationRef);
  6313. if (bootstrappedComponentRef !== ref.components[0]) {
  6314. return;
  6315. }
  6316. const router = injector.get(Router);
  6317. const bootstrapDone = injector.get(BOOTSTRAP_DONE);
  6318. if (injector.get(INITIAL_NAVIGATION) === 1 /* InitialNavigation.EnabledNonBlocking */) {
  6319. router.initialNavigation();
  6320. }
  6321. injector.get(ROUTER_PRELOADER, null, InjectFlags.Optional)?.setUpPreloading();
  6322. injector.get(ROUTER_SCROLLER, null, InjectFlags.Optional)?.init();
  6323. router.resetRootComponentType(ref.componentTypes[0]);
  6324. if (!bootstrapDone.closed) {
  6325. bootstrapDone.next();
  6326. bootstrapDone.complete();
  6327. bootstrapDone.unsubscribe();
  6328. }
  6329. };
  6330. }
  6331. /**
  6332. * A subject used to indicate that the bootstrapping phase is done. When initial navigation is
  6333. * `enabledBlocking`, the first navigation waits until bootstrapping is finished before continuing
  6334. * to the activation phase.
  6335. */
  6336. const BOOTSTRAP_DONE = new InjectionToken((typeof ngDevMode === 'undefined' || ngDevMode) ? 'bootstrap done indicator' : '', {
  6337. factory: () => {
  6338. return new Subject();
  6339. }
  6340. });
  6341. const INITIAL_NAVIGATION = new InjectionToken((typeof ngDevMode === 'undefined' || ngDevMode) ? 'initial navigation' : '', { providedIn: 'root', factory: () => 1 /* InitialNavigation.EnabledNonBlocking */ });
  6342. /**
  6343. * Configures initial navigation to start before the root component is created.
  6344. *
  6345. * The bootstrap is blocked until the initial navigation is complete. This value is required for
  6346. * [server-side rendering](guide/universal) to work.
  6347. *
  6348. * @usageNotes
  6349. *
  6350. * Basic example of how you can enable this navigation behavior:
  6351. * ```
  6352. * const appRoutes: Routes = [];
  6353. * bootstrapApplication(AppComponent,
  6354. * {
  6355. * providers: [
  6356. * provideRouter(appRoutes, withEnabledBlockingInitialNavigation())
  6357. * ]
  6358. * }
  6359. * );
  6360. * ```
  6361. *
  6362. * @see `provideRouter`
  6363. *
  6364. * @publicApi
  6365. * @returns A set of providers for use with `provideRouter`.
  6366. */
  6367. function withEnabledBlockingInitialNavigation() {
  6368. const providers = [
  6369. { provide: INITIAL_NAVIGATION, useValue: 0 /* InitialNavigation.EnabledBlocking */ },
  6370. {
  6371. provide: APP_INITIALIZER,
  6372. multi: true,
  6373. deps: [Injector],
  6374. useFactory: (injector) => {
  6375. const locationInitialized = injector.get(LOCATION_INITIALIZED, Promise.resolve());
  6376. return () => {
  6377. return locationInitialized.then(() => {
  6378. return new Promise(resolve => {
  6379. const router = injector.get(Router);
  6380. const bootstrapDone = injector.get(BOOTSTRAP_DONE);
  6381. afterNextNavigation(router, () => {
  6382. // Unblock APP_INITIALIZER in case the initial navigation was canceled or errored
  6383. // without a redirect.
  6384. resolve(true);
  6385. });
  6386. injector.get(NavigationTransitions).afterPreactivation = () => {
  6387. // Unblock APP_INITIALIZER once we get to `afterPreactivation`. At this point, we
  6388. // assume activation will complete successfully (even though this is not
  6389. // guaranteed).
  6390. resolve(true);
  6391. return bootstrapDone.closed ? of(void 0) : bootstrapDone;
  6392. };
  6393. router.initialNavigation();
  6394. });
  6395. });
  6396. };
  6397. }
  6398. },
  6399. ];
  6400. return routerFeature(2 /* RouterFeatureKind.EnabledBlockingInitialNavigationFeature */, providers);
  6401. }
  6402. /**
  6403. * Disables initial navigation.
  6404. *
  6405. * Use if there is a reason to have more control over when the router starts its initial navigation
  6406. * due to some complex initialization logic.
  6407. *
  6408. * @usageNotes
  6409. *
  6410. * Basic example of how you can disable initial navigation:
  6411. * ```
  6412. * const appRoutes: Routes = [];
  6413. * bootstrapApplication(AppComponent,
  6414. * {
  6415. * providers: [
  6416. * provideRouter(appRoutes, withDisabledInitialNavigation())
  6417. * ]
  6418. * }
  6419. * );
  6420. * ```
  6421. *
  6422. * @see `provideRouter`
  6423. *
  6424. * @returns A set of providers for use with `provideRouter`.
  6425. *
  6426. * @publicApi
  6427. */
  6428. function withDisabledInitialNavigation() {
  6429. const providers = [
  6430. {
  6431. provide: APP_INITIALIZER,
  6432. multi: true,
  6433. useFactory: () => {
  6434. const router = inject(Router);
  6435. return () => {
  6436. router.setUpLocationChangeListener();
  6437. };
  6438. }
  6439. },
  6440. { provide: INITIAL_NAVIGATION, useValue: 2 /* InitialNavigation.Disabled */ }
  6441. ];
  6442. return routerFeature(3 /* RouterFeatureKind.DisabledInitialNavigationFeature */, providers);
  6443. }
  6444. /**
  6445. * Enables logging of all internal navigation events to the console.
  6446. * Extra logging might be useful for debugging purposes to inspect Router event sequence.
  6447. *
  6448. * @usageNotes
  6449. *
  6450. * Basic example of how you can enable debug tracing:
  6451. * ```
  6452. * const appRoutes: Routes = [];
  6453. * bootstrapApplication(AppComponent,
  6454. * {
  6455. * providers: [
  6456. * provideRouter(appRoutes, withDebugTracing())
  6457. * ]
  6458. * }
  6459. * );
  6460. * ```
  6461. *
  6462. * @see `provideRouter`
  6463. *
  6464. * @returns A set of providers for use with `provideRouter`.
  6465. *
  6466. * @publicApi
  6467. */
  6468. function withDebugTracing() {
  6469. let providers = [];
  6470. if (typeof ngDevMode === 'undefined' || ngDevMode) {
  6471. providers = [{
  6472. provide: ENVIRONMENT_INITIALIZER,
  6473. multi: true,
  6474. useFactory: () => {
  6475. const router = inject(Router);
  6476. return () => router.events.subscribe((e) => {
  6477. // tslint:disable:no-console
  6478. console.group?.(`Router Event: ${e.constructor.name}`);
  6479. console.log(stringifyEvent(e));
  6480. console.log(e);
  6481. console.groupEnd?.();
  6482. // tslint:enable:no-console
  6483. });
  6484. }
  6485. }];
  6486. }
  6487. else {
  6488. providers = [];
  6489. }
  6490. return routerFeature(1 /* RouterFeatureKind.DebugTracingFeature */, providers);
  6491. }
  6492. const ROUTER_PRELOADER = new InjectionToken((typeof ngDevMode === 'undefined' || ngDevMode) ? 'router preloader' : '');
  6493. /**
  6494. * Allows to configure a preloading strategy to use. The strategy is configured by providing a
  6495. * reference to a class that implements a `PreloadingStrategy`.
  6496. *
  6497. * @usageNotes
  6498. *
  6499. * Basic example of how you can configure preloading:
  6500. * ```
  6501. * const appRoutes: Routes = [];
  6502. * bootstrapApplication(AppComponent,
  6503. * {
  6504. * providers: [
  6505. * provideRouter(appRoutes, withPreloading(PreloadAllModules))
  6506. * ]
  6507. * }
  6508. * );
  6509. * ```
  6510. *
  6511. * @see `provideRouter`
  6512. *
  6513. * @param preloadingStrategy A reference to a class that implements a `PreloadingStrategy` that
  6514. * should be used.
  6515. * @returns A set of providers for use with `provideRouter`.
  6516. *
  6517. * @publicApi
  6518. */
  6519. function withPreloading(preloadingStrategy) {
  6520. const providers = [
  6521. { provide: ROUTER_PRELOADER, useExisting: RouterPreloader },
  6522. { provide: PreloadingStrategy, useExisting: preloadingStrategy },
  6523. ];
  6524. return routerFeature(0 /* RouterFeatureKind.PreloadingFeature */, providers);
  6525. }
  6526. /**
  6527. * Allows to provide extra parameters to configure Router.
  6528. *
  6529. * @usageNotes
  6530. *
  6531. * Basic example of how you can provide extra configuration options:
  6532. * ```
  6533. * const appRoutes: Routes = [];
  6534. * bootstrapApplication(AppComponent,
  6535. * {
  6536. * providers: [
  6537. * provideRouter(appRoutes, withRouterConfig({
  6538. * onSameUrlNavigation: 'reload'
  6539. * }))
  6540. * ]
  6541. * }
  6542. * );
  6543. * ```
  6544. *
  6545. * @see `provideRouter`
  6546. *
  6547. * @param options A set of parameters to configure Router, see `RouterConfigOptions` for
  6548. * additional information.
  6549. * @returns A set of providers for use with `provideRouter`.
  6550. *
  6551. * @publicApi
  6552. */
  6553. function withRouterConfig(options) {
  6554. const providers = [
  6555. { provide: ROUTER_CONFIGURATION, useValue: options },
  6556. ];
  6557. return routerFeature(5 /* RouterFeatureKind.RouterConfigurationFeature */, providers);
  6558. }
  6559. /**
  6560. * Provides the location strategy that uses the URL fragment instead of the history API.
  6561. *
  6562. * @usageNotes
  6563. *
  6564. * Basic example of how you can use the hash location option:
  6565. * ```
  6566. * const appRoutes: Routes = [];
  6567. * bootstrapApplication(AppComponent,
  6568. * {
  6569. * providers: [
  6570. * provideRouter(appRoutes, withHashLocation())
  6571. * ]
  6572. * }
  6573. * );
  6574. * ```
  6575. *
  6576. * @see `provideRouter`
  6577. * @see `HashLocationStrategy`
  6578. *
  6579. * @returns A set of providers for use with `provideRouter`.
  6580. *
  6581. * @publicApi
  6582. */
  6583. function withHashLocation() {
  6584. const providers = [
  6585. { provide: LocationStrategy, useClass: HashLocationStrategy },
  6586. ];
  6587. return routerFeature(5 /* RouterFeatureKind.RouterConfigurationFeature */, providers);
  6588. }
  6589. /**
  6590. * Subscribes to the Router's navigation events and calls the given function when a
  6591. * `NavigationError` happens.
  6592. *
  6593. * This function is run inside application's injection context so you can use the `inject` function.
  6594. *
  6595. * @usageNotes
  6596. *
  6597. * Basic example of how you can use the error handler option:
  6598. * ```
  6599. * const appRoutes: Routes = [];
  6600. * bootstrapApplication(AppComponent,
  6601. * {
  6602. * providers: [
  6603. * provideRouter(appRoutes, withNavigationErrorHandler((e: NavigationError) =>
  6604. * inject(MyErrorTracker).trackError(e)))
  6605. * ]
  6606. * }
  6607. * );
  6608. * ```
  6609. *
  6610. * @see `NavigationError`
  6611. * @see `inject`
  6612. * @see `EnvironmentInjector#runInContext`
  6613. *
  6614. * @returns A set of providers for use with `provideRouter`.
  6615. *
  6616. * @publicApi
  6617. */
  6618. function withNavigationErrorHandler(fn) {
  6619. const providers = [{
  6620. provide: ENVIRONMENT_INITIALIZER,
  6621. multi: true,
  6622. useValue: () => {
  6623. const injector = inject(EnvironmentInjector);
  6624. inject(Router).events.subscribe((e) => {
  6625. if (e instanceof NavigationError) {
  6626. injector.runInContext(() => fn(e));
  6627. }
  6628. });
  6629. }
  6630. }];
  6631. return routerFeature(7 /* RouterFeatureKind.NavigationErrorHandlerFeature */, providers);
  6632. }
  6633. /**
  6634. * Enables binding information from the `Router` state directly to the inputs of the component in
  6635. * `Route` configurations.
  6636. *
  6637. * @usageNotes
  6638. *
  6639. * Basic example of how you can enable the feature:
  6640. * ```
  6641. * const appRoutes: Routes = [];
  6642. * bootstrapApplication(AppComponent,
  6643. * {
  6644. * providers: [
  6645. * provideRouter(appRoutes, withComponentInputBinding())
  6646. * ]
  6647. * }
  6648. * );
  6649. * ```
  6650. *
  6651. * @returns A set of providers for use with `provideRouter`.
  6652. */
  6653. function withComponentInputBinding() {
  6654. const providers = [
  6655. RoutedComponentInputBinder,
  6656. { provide: INPUT_BINDER, useExisting: RoutedComponentInputBinder },
  6657. ];
  6658. return routerFeature(8 /* RouterFeatureKind.ComponentInputBindingFeature */, providers);
  6659. }
  6660. /**
  6661. * The directives defined in the `RouterModule`.
  6662. */
  6663. const ROUTER_DIRECTIVES = [RouterOutlet, RouterLink, RouterLinkActive, ɵEmptyOutletComponent];
  6664. /**
  6665. * @docsNotRequired
  6666. */
  6667. const ROUTER_FORROOT_GUARD = new InjectionToken((typeof ngDevMode === 'undefined' || ngDevMode) ? 'router duplicate forRoot guard' :
  6668. 'ROUTER_FORROOT_GUARD');
  6669. // TODO(atscott): All of these except `ActivatedRoute` are `providedIn: 'root'`. They are only kept
  6670. // here to avoid a breaking change whereby the provider order matters based on where the
  6671. // `RouterModule`/`RouterTestingModule` is imported. These can/should be removed as a "breaking"
  6672. // change in a major version.
  6673. const ROUTER_PROVIDERS = [
  6674. Location,
  6675. { provide: UrlSerializer, useClass: DefaultUrlSerializer },
  6676. Router,
  6677. ChildrenOutletContexts,
  6678. { provide: ActivatedRoute, useFactory: rootRoute, deps: [Router] },
  6679. RouterConfigLoader,
  6680. // Only used to warn when `provideRoutes` is used without `RouterModule` or `provideRouter`. Can
  6681. // be removed when `provideRoutes` is removed.
  6682. (typeof ngDevMode === 'undefined' || ngDevMode) ? { provide: ROUTER_IS_PROVIDED, useValue: true } :
  6683. [],
  6684. ];
  6685. function routerNgProbeToken() {
  6686. return new NgProbeToken('Router', Router);
  6687. }
  6688. /**
  6689. * @description
  6690. *
  6691. * Adds directives and providers for in-app navigation among views defined in an application.
  6692. * Use the Angular `Router` service to declaratively specify application states and manage state
  6693. * transitions.
  6694. *
  6695. * You can import this NgModule multiple times, once for each lazy-loaded bundle.
  6696. * However, only one `Router` service can be active.
  6697. * To ensure this, there are two ways to register routes when importing this module:
  6698. *
  6699. * * The `forRoot()` method creates an `NgModule` that contains all the directives, the given
  6700. * routes, and the `Router` service itself.
  6701. * * The `forChild()` method creates an `NgModule` that contains all the directives and the given
  6702. * routes, but does not include the `Router` service.
  6703. *
  6704. * @see [Routing and Navigation guide](guide/router) for an
  6705. * overview of how the `Router` service should be used.
  6706. *
  6707. * @publicApi
  6708. */
  6709. class RouterModule {
  6710. constructor(guard) { }
  6711. /**
  6712. * Creates and configures a module with all the router providers and directives.
  6713. * Optionally sets up an application listener to perform an initial navigation.
  6714. *
  6715. * When registering the NgModule at the root, import as follows:
  6716. *
  6717. * ```
  6718. * @NgModule({
  6719. * imports: [RouterModule.forRoot(ROUTES)]
  6720. * })
  6721. * class MyNgModule {}
  6722. * ```
  6723. *
  6724. * @param routes An array of `Route` objects that define the navigation paths for the application.
  6725. * @param config An `ExtraOptions` configuration object that controls how navigation is performed.
  6726. * @return The new `NgModule`.
  6727. *
  6728. */
  6729. static forRoot(routes, config) {
  6730. return {
  6731. ngModule: RouterModule,
  6732. providers: [
  6733. ROUTER_PROVIDERS,
  6734. (typeof ngDevMode === 'undefined' || ngDevMode) ?
  6735. (config?.enableTracing ? withDebugTracing().ɵproviders : []) :
  6736. [],
  6737. { provide: ROUTES, multi: true, useValue: routes },
  6738. {
  6739. provide: ROUTER_FORROOT_GUARD,
  6740. useFactory: provideForRootGuard,
  6741. deps: [[Router, new Optional(), new SkipSelf()]]
  6742. },
  6743. { provide: ROUTER_CONFIGURATION, useValue: config ? config : {} },
  6744. config?.useHash ? provideHashLocationStrategy() : providePathLocationStrategy(),
  6745. provideRouterScroller(),
  6746. config?.preloadingStrategy ? withPreloading(config.preloadingStrategy).ɵproviders : [],
  6747. { provide: NgProbeToken, multi: true, useFactory: routerNgProbeToken },
  6748. config?.initialNavigation ? provideInitialNavigation(config) : [],
  6749. config?.bindToComponentInputs ? withComponentInputBinding().ɵproviders : [],
  6750. provideRouterInitializer(),
  6751. ],
  6752. };
  6753. }
  6754. /**
  6755. * Creates a module with all the router directives and a provider registering routes,
  6756. * without creating a new Router service.
  6757. * When registering for submodules and lazy-loaded submodules, create the NgModule as follows:
  6758. *
  6759. * ```
  6760. * @NgModule({
  6761. * imports: [RouterModule.forChild(ROUTES)]
  6762. * })
  6763. * class MyNgModule {}
  6764. * ```
  6765. *
  6766. * @param routes An array of `Route` objects that define the navigation paths for the submodule.
  6767. * @return The new NgModule.
  6768. *
  6769. */
  6770. static forChild(routes) {
  6771. return {
  6772. ngModule: RouterModule,
  6773. providers: [{ provide: ROUTES, multi: true, useValue: routes }],
  6774. };
  6775. }
  6776. static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "16.0.4", ngImport: i0, type: RouterModule, deps: [{ token: ROUTER_FORROOT_GUARD, optional: true }], target: i0.ɵɵFactoryTarget.NgModule }); }
  6777. static { this.ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "14.0.0", version: "16.0.4", ngImport: i0, type: RouterModule, imports: [RouterOutlet, RouterLink, RouterLinkActive, ɵEmptyOutletComponent], exports: [RouterOutlet, RouterLink, RouterLinkActive, ɵEmptyOutletComponent] }); }
  6778. static { this.ɵinj = i0.ɵɵngDeclareInjector({ minVersion: "12.0.0", version: "16.0.4", ngImport: i0, type: RouterModule }); }
  6779. }
  6780. i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "16.0.4", ngImport: i0, type: RouterModule, decorators: [{
  6781. type: NgModule,
  6782. args: [{
  6783. imports: ROUTER_DIRECTIVES,
  6784. exports: ROUTER_DIRECTIVES,
  6785. }]
  6786. }], ctorParameters: function () { return [{ type: undefined, decorators: [{
  6787. type: Optional
  6788. }, {
  6789. type: Inject,
  6790. args: [ROUTER_FORROOT_GUARD]
  6791. }] }]; } });
  6792. /**
  6793. * For internal use by `RouterModule` only. Note that this differs from `withInMemoryRouterScroller`
  6794. * because it reads from the `ExtraOptions` which should not be used in the standalone world.
  6795. */
  6796. function provideRouterScroller() {
  6797. return {
  6798. provide: ROUTER_SCROLLER,
  6799. useFactory: () => {
  6800. const viewportScroller = inject(ViewportScroller);
  6801. const zone = inject(NgZone);
  6802. const config = inject(ROUTER_CONFIGURATION);
  6803. const transitions = inject(NavigationTransitions);
  6804. const urlSerializer = inject(UrlSerializer);
  6805. if (config.scrollOffset) {
  6806. viewportScroller.setOffset(config.scrollOffset);
  6807. }
  6808. return new RouterScroller(urlSerializer, transitions, viewportScroller, zone, config);
  6809. },
  6810. };
  6811. }
  6812. // Note: For internal use only with `RouterModule`. Standalone setup via `provideRouter` should
  6813. // provide hash location directly via `{provide: LocationStrategy, useClass: HashLocationStrategy}`.
  6814. function provideHashLocationStrategy() {
  6815. return { provide: LocationStrategy, useClass: HashLocationStrategy };
  6816. }
  6817. // Note: For internal use only with `RouterModule`. Standalone setup via `provideRouter` does not
  6818. // need this at all because `PathLocationStrategy` is the default factory for `LocationStrategy`.
  6819. function providePathLocationStrategy() {
  6820. return { provide: LocationStrategy, useClass: PathLocationStrategy };
  6821. }
  6822. function provideForRootGuard(router) {
  6823. if ((typeof ngDevMode === 'undefined' || ngDevMode) && router) {
  6824. throw new ɵRuntimeError(4007 /* RuntimeErrorCode.FOR_ROOT_CALLED_TWICE */, `The Router was provided more than once. This can happen if 'forRoot' is used outside of the root injector.` +
  6825. ` Lazy loaded modules should use RouterModule.forChild() instead.`);
  6826. }
  6827. return 'guarded';
  6828. }
  6829. // Note: For internal use only with `RouterModule`. Standalone router setup with `provideRouter`
  6830. // users call `withXInitialNavigation` directly.
  6831. function provideInitialNavigation(config) {
  6832. return [
  6833. config.initialNavigation === 'disabled' ? withDisabledInitialNavigation().ɵproviders : [],
  6834. config.initialNavigation === 'enabledBlocking' ?
  6835. withEnabledBlockingInitialNavigation().ɵproviders :
  6836. [],
  6837. ];
  6838. }
  6839. // TODO(atscott): This should not be in the public API
  6840. /**
  6841. * A [DI token](guide/glossary/#di-token) for the router initializer that
  6842. * is called after the app is bootstrapped.
  6843. *
  6844. * @publicApi
  6845. */
  6846. const ROUTER_INITIALIZER = new InjectionToken((typeof ngDevMode === 'undefined' || ngDevMode) ? 'Router Initializer' : '');
  6847. function provideRouterInitializer() {
  6848. return [
  6849. // ROUTER_INITIALIZER token should be removed. It's public API but shouldn't be. We can just
  6850. // have `getBootstrapListener` directly attached to APP_BOOTSTRAP_LISTENER.
  6851. { provide: ROUTER_INITIALIZER, useFactory: getBootstrapListener },
  6852. { provide: APP_BOOTSTRAP_LISTENER, multi: true, useExisting: ROUTER_INITIALIZER },
  6853. ];
  6854. }
  6855. /**
  6856. * Maps an array of injectable classes with canMatch functions to an array of equivalent
  6857. * `CanMatchFn` for use in a `Route` definition.
  6858. *
  6859. * Usage {@example router/utils/functional_guards.ts region='CanActivate'}
  6860. *
  6861. * @publicApi
  6862. * @see Route
  6863. */
  6864. function mapToCanMatch(providers) {
  6865. return providers.map(provider => (...params) => inject(provider).canMatch(...params));
  6866. }
  6867. /**
  6868. * Maps an array of injectable classes with canActivate functions to an array of equivalent
  6869. * `CanActivateFn` for use in a `Route` definition.
  6870. *
  6871. * Usage {@example router/utils/functional_guards.ts region='CanActivate'}
  6872. *
  6873. * @publicApi
  6874. * @see Route
  6875. */
  6876. function mapToCanActivate(providers) {
  6877. return providers.map(provider => (...params) => inject(provider).canActivate(...params));
  6878. }
  6879. /**
  6880. * Maps an array of injectable classes with canActivateChild functions to an array of equivalent
  6881. * `CanActivateChildFn` for use in a `Route` definition.
  6882. *
  6883. * Usage {@example router/utils/functional_guards.ts region='CanActivate'}
  6884. *
  6885. * @publicApi
  6886. * @see Route
  6887. */
  6888. function mapToCanActivateChild(providers) {
  6889. return providers.map(provider => (...params) => inject(provider).canActivateChild(...params));
  6890. }
  6891. /**
  6892. * Maps an array of injectable classes with canDeactivate functions to an array of equivalent
  6893. * `CanDeactivateFn` for use in a `Route` definition.
  6894. *
  6895. * Usage {@example router/utils/functional_guards.ts region='CanActivate'}
  6896. *
  6897. * @publicApi
  6898. * @see Route
  6899. */
  6900. function mapToCanDeactivate(providers) {
  6901. return providers.map(provider => (...params) => inject(provider).canDeactivate(...params));
  6902. }
  6903. /**
  6904. * Maps an injectable class with a resolve function to an equivalent `ResolveFn`
  6905. * for use in a `Route` definition.
  6906. *
  6907. * Usage {@example router/utils/functional_guards.ts region='Resolve'}
  6908. *
  6909. * @publicApi
  6910. * @see Route
  6911. */
  6912. function mapToResolve(provider) {
  6913. return (...params) => inject(provider).resolve(...params);
  6914. }
  6915. /**
  6916. * @module
  6917. * @description
  6918. * Entry point for all public APIs of the router package.
  6919. */
  6920. /**
  6921. * @publicApi
  6922. */
  6923. const VERSION = new Version('16.0.4');
  6924. /**
  6925. * @module
  6926. * @description
  6927. * Entry point for all public APIs of this package.
  6928. */
  6929. // This file only reexports content of the `src` folder. Keep it that way.
  6930. // This file is not used to build this module. It is only used during editing
  6931. /**
  6932. * Generated bundle index. Do not edit.
  6933. */
  6934. export { ActivatedRoute, ActivatedRouteSnapshot, ActivationEnd, ActivationStart, BaseRouteReuseStrategy, ChildActivationEnd, ChildActivationStart, ChildrenOutletContexts, DefaultTitleStrategy, DefaultUrlSerializer, GuardsCheckEnd, GuardsCheckStart, NavigationCancel, NavigationEnd, NavigationError, NavigationSkipped, NavigationStart, NoPreloading, OutletContext, PRIMARY_OUTLET, PreloadAllModules, PreloadingStrategy, ROUTER_CONFIGURATION, ROUTER_INITIALIZER, ROUTES, ResolveEnd, ResolveStart, RouteConfigLoadEnd, RouteConfigLoadStart, RouteReuseStrategy, Router, RouterEvent, RouterLink, RouterLinkActive, RouterLink as RouterLinkWithHref, RouterModule, RouterOutlet, RouterPreloader, RouterState, RouterStateSnapshot, RoutesRecognized, Scroll, TitleStrategy, UrlHandlingStrategy, UrlSegment, UrlSegmentGroup, UrlSerializer, UrlTree, VERSION, convertToParamMap, createUrlTreeFromSnapshot, defaultUrlMatcher, mapToCanActivate, mapToCanActivateChild, mapToCanDeactivate, mapToCanMatch, mapToResolve, provideRouter, provideRoutes, withComponentInputBinding, withDebugTracing, withDisabledInitialNavigation, withEnabledBlockingInitialNavigation, withHashLocation, withInMemoryScrolling, withNavigationErrorHandler, withPreloading, withRouterConfig, ɵEmptyOutletComponent, ROUTER_PROVIDERS as ɵROUTER_PROVIDERS, afterNextNavigation as ɵafterNextNavigation };
  6935. //# sourceMappingURL=router.mjs.map