router.js 201KB

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