router.js 217 KB

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