TypeScript and Angular workshop

Post on 21-Apr-2017

44 views 1 download

Transcript of TypeScript and Angular workshop

GUL-UC3M

TypeScript& AngularWorkshop

30 de Marzo de 2017

Isabel Matas Rabadán & José Manuel García García

GUL-UC3M

TypeScript& AngularWorkshop

30 de Marzo de 2017

Isabel Matas Rabadán & José Manuel García García

Whoarewe?

IsabelMatasBecArquitecta JavaScript

Sema GarcíaArquitecto JavaScript

Disclaimer

• Time&Materials• Workshoproom• Initialapproach• Tightslottime• Notrequiredlaptop• Github tagstotrainathome• Sessionrecorded?

Agenda

• TypeScript• Angularv4.0• The7keycoreconcepts• AngularCLI• OurAngularapp

TypeScript

TypeScript

IntroductiontoTypeScript

• Features:• Generatedcode100%compatiblewithbrowsers.• Stronglytyped.• Compilationtimeerrors.• Intellisense.• Interfaces.• Classes.• Methodandpropertiesmodifiers(private,protected…).• Constructorsandstaticmembers.• Getters/Setters.• Inheritance.• Modules.• Imports,exports.• Generics.• Debuggingwithsourcemaps.• Definitiontypefiles(*.d.ts).

IntroductiontoTypeScriptTYPESCR IPT… WHO ARE YOU?

Shedding light on JavaScript to whom have lost hope…

IntroductiontoTypeScript

• Poner capturas delVCydecir sólo una frase como mica:“Havenidoparasalvarme”->hero• Quemeavises delos errores• Quemeescribas elcódigo• Quete asegures quelos demás seenteran (refactor)• Quemeresuelvas mis dudas (doc)

TYPESCR IPT… WHO ARE YOU?

has definetely come to…

IntroductiontoTypeScript

…Warn us the errorsduring coding phase(compilation time)…

IntroductiontoTypeScript

…Tell us what we cando…

IntroductiontoTypeScript

…Help us when we’ve forgot something…

IntroductiontoTypeScript

IntroductiontoTypeScript• TypeScript willalwaystranspile toJavaScript,evenwhentherearewarnings.

• Anappcouldhavesimulateously.ts and.js code(asusuallyis).

• ATypeScript projecthastohaveafilecalledtsconfig.json initsrootpathfolder.

IntroductiontoTypeScriptSomefieldsofinterest:

• declaration:generatescorrespondingd.ts files.• emitDecoratorMetadata:emitdesign-typemetadatafordecorateddeclarationsinsource.• experimentalDecorators:enablesexperimentalsupportforES7decorators.• lib:specifylibraryfiletobeincludedinthecompilation.RequiresTypeScript version2.0orlater.• module:specifymodulecodegeneration:'none','CommonJS','Amd','System','UMD',or'es2015'.• moduleResolution:specifiesmoduleresolutionstrategy:'node'(Node)or'classic'(TypeScript pre1.6).• outDir:redirectoutputstructuretothedirectory.• sourceMap:generatescorresponding'.map'file.• target:specifyECMAScripttargetversion.Permittedvaluesare'es3','es5','es2015','es2016','es2017'or'esnext'.• typeRoots:specifylistofdirectoryfortypedefinitionfilestobeinclude.RequiresTypeScript version2.0orlater.• types:typedeclarationfilestobeincludedincompilation.RequiresTypeScript version2.0orlater.• strictNullChecks:enablestrictnullchecks.RequiresTypeScript version2.0orlater.

Moreinfo:here.

IntroductiontoTypeScript• It’smandatorytodeclaretheattributes.• Wecanusevisibilitymodifiers:public(default),protected&private.

• Toreducetheboilerplate,theconstructorparams areconsiderasattributestoo:

• Itwillbevalidwhilethevariablespassedasargumentssatisfyitsstructure…

IntroductiontoTypeScript• Writingclasses,interfacesandobjecttypes.

• Aninterfacecanbeconsiderlikeaobjecttype,becauseguaranteeitsstructure.

• Ifaclassdoesnotsatisfytheinterfacestructure,itwillthrowanerror…

IntroductiontoTypeScript• Writingasubclass(inheritance)thatimplementsaninterface

(“d”avoidsthecompilationerror)

IntroductiontoTypeScript• Writinganunionandtypeguards.

• Howcancontrolthissituation?

!!

"

IntroductiontoTypeScript

• TypeScript supportsgettersandsetters asawayofinterceptingaccessestoamemberofanobject.Thisgiveusawayofhavingfiner-grainedcontroloverhowamemberisaccessedoneachobject.

IntroductiontoTypeScript• TypeScript alsoallowustodefinestaticproperties/methodsbesidesinstanceproperties/methods.

• Wecanuseitdirectlywithoutaninstance:

• Andalsowecancreateinstancefromit:

IntroductiontoTypeScript

• Accessmodifiers:private,protected,public,readonly• Private:whenamemberismarkedasprivate,itcannotbeaccessedfromoutsideofitscontainingclass.

• Protected:thismodifiersactsmuchliketheprivatemodifierwiththeexceptionthatprotectedelementscanalsobeaccessedbyinstancesofderivingclasses.Thatelementcouldbeusedfromwithinaninstancemethodofsubclass.Evenaconstructorcouldbemarkedasprotected,whatthatmeansthatclasscannotbeinstantiatedoutsideofitscontainingclass,butcanbeextended.

• Public:bydefault,ifwedon’tspecifyanymodifier,eachpropertyandmethodwillbepublic.Allpublicelementswillbevisibleforanyone.

• Readonly:propertiesmarkedasreadonlymustbeinitializedattheirdeclarationorintheconstructor.Laterwillbenotpossible.

Who comesfrom AngularJS?

Angular… WTHis that?

• Fromframeworktoplatform

DependencyInjection Decorators Zones

Compile Change Render

Material Mobile Universal

CLI LanguageServices Augury

ngUpgrade

Router

Animation

i18n

Angular… WTHis that?

• FullDevelopmentStack

SEMVERandAngularversions• 2.0• 2.1• 2.2• 2.3• 2.4• 3.0• 4.0

Thesuper-tooltotherescue:AngularCLI

• AngularCLI(CommandLineInterface)• Recom.:Node7.x&NPM4.x• npm install–g@angular/cli

The7magnificent

Modules

Components

Templates

Databinding

Structuraldirectives

Services

DependencyInjection

Createanewproject

ng new project-name –style=scss

Createanewproject

Whatthingstherearehere?

Link

index.html

bundle.js

Link references

styles.(s)css

styles

references

src

Thebasicdependencyflow

Link

import

polyfills.ts

main.ts

Vendor.js

3rd libraries

Root Component (bundle.js)

app.module.ts

app.component.ts

app.routes.ts

import

Applicationbootstrapping

• Allapphas,atleast,onemodule:therootone

Applicationbootstrapping

• TherootAppModule(conventionname).• Modulemarkedwith@NgModule decorator.• Angularusesdecoratorstoknowhowtocompileandlaunchtheapp.

Applicationbootstrapping

Declarations:• Whichcomponentswillbelongtothatmodule.• Theonlydeclarableelementsallowedherearecomponents,pipesanddirectives.

Applicationbootstrapping

Imports:

• Thedeclarationofwhichothermodulesthecurrentmoduleneeds.• WecanimporteithercoreAngularmodulesorourones.

Applicationbootstrapping

Imports:• Usually,wewillonlyhaveonebootstrappedcomponent.• Thisbootstrapprocessdefinesthecomponentsthatareinstantiated.

Applicationbootstrapping

Rootcomponent

ModulesandAppModule

•Moduleconcept/strategy.• TheAngularmodulesaresimilartoES6modules.• AmoduleistheminimumunitofcompilationanddistributionofAngularelements,definingthecompilationcontextoftheircomponents.• Willhelpustoorganizeourcode,groupingtheelementswithrelatedfeatures,makingthemmorereusable.• Onecomponentcanonlybedeclaredinonemodule.• ManyAngularthirdlibrariesareavailableasNgModule’s toimporttheminsideof“declaration”propertyofonecomponent.• TheAppModule willalwaysdeclaretheAppComponent byconvention.

AppComponentComponenttree.

AppComponent

AppComponent

• @Componentdecorator:• selector• template[Url]• style[Urls]• providers• animations• …

ComponentsandWebComponents

Components

• Componentsbenefits.• Reusability.• Complexity.• Legibility.• Testability.

Bindings

• Waystodatabind

Addinganothercomponent

ng g component XXX

Allourcomponents

• AppComponent• HomeComponent• SeriesComponent• CharacterComponent

AngularServices

Services

• Theunderlyingconcept:dependencyinjection(DI).• “Don’tcallyouus,wewilldoit”.• Benefits:• Elementsdecoupled.• Separatedlogic.• Reusable.• Testable.

Addingaservice

ng g service XXX

Metadataforaservice

• Add@Injectable() decorator:

Registeringaservice

• Addittoproviders entrypropertyinamodule:

Usingaservice

• Importtheservice.• Addthedependencytotheconstructorofcallerclass:

Usingcoreservices

• Andifweneedmoredependencies?• Rememberthatifwespecifysomeparams inconstructor,itwillcreatethoseattributesdirectly.• Remembertoaddalsothemodule(ifitbelongstoadifferentemodule).

Navigating/AngularRouter

• Appcomposedbydifferentcomponents/views

Navigating/Router

• Definingroutes

Navigating/Router

• Wherewillberenderedmycomponents?

Navigating/Router

• Nowwehaveconfiguration,renderarea,but… how canwe navigatetoanother component?

RouterModule

• The last step is todefinean special type ofmodulefor the routes,andtomake theme available for the rest ofthe app:

Navigating/Router

• Toaccess toURLparams we cando:

• Inject the service.• Onceinjected the service:

Callingtobackend

Callingtobackend

• Asrecommendation(duetoitsasynchronousnature),allbackendcallsshouldbeencapsulatedinsideaservice.• Theserviceoffersusthemainverbs:GET,POST,PUT,DELETE.• Themostimportantpartisthat,bydefault,theresultisanobservableinsteadofapromise.So,theimportneededare:

Callingtobackend

• Afterthat,insidetheservice,theimplementation:

Remember:AsweareusingTypeScript,weshouldspecifythereturntypeofthefunction.

Callingtobackend

• But,thatobservable… How canIuseit?

• Ofcourse,we canchain moreRx operators:

Observables:thereactiveway

Observablesinareactiveworld

• Reactiveprogrammingisprogrammingwithasynchronousdatastreams:eventbusesortypicalclickeventsarereallyanasync eventstream,onwhichwecanobserveanddostuff.

Observableexample

• Grayboxesarefunctionsthattransformsonestreamintoanother.

• First,weaccumulateclicksinlists,whenever250msofsilencehashappened(throttle).

• Thisresultisastreamoflists,fromwhichweapplyotheroperationtomapeachlisttoanintegermatchingitslength.

• Finally,weignore1integersusingthefilteroper.• Nowwecansuscribe (orlisten)toit,andreacthowwewishwiththosevalues.

Observableorpromise?

• Whyobservablesarebetterthanpromises?

Promises

• Handlesasingleeventwhenanasync operationcompletesorfails

• Returnsasinglevalue• SupportedinES6

Observables

• Handlesastream(zeroormorethanzeroevents)

• Offersthefeaturesprovidedbypromisesandmore

• Theyarecancellable• Theyhaveusefuloperatorslikemap,reduce,retry...

Observableorpromise?

Pipes:transformingdata

Addingapipe

ng g pipe XXX

Pipes

• Thepurposeofapipeistotransformdisplayedvalueswithinatemplate.• Oneadvantageofpipesconsistofawaytowritedisplay-valuestransformationsthatwecandeclareinHTMLtemplates,insideoftheinterpolationexpression.

Pipes

• Thepipescanbeparameterized:

• Thepipesalsocanbechained:

Pipes

• Imagineyouwanttocountthelengthofastringtooutputittotheuser.• Apipecanbetheperfectsolution,becauseitcanbereusedanywherewithoutbecoupledtoacomponent.

Testing… testing everywhere

• Thetestingis,sometimes,unfortunatelyunderestimated,butitisasimportant(orevenmore)thanthepropercode.Moreover,someauthorssaythatthetestingcodeisanotherwayofdocumentation.

• Tosummarizetheideaoftesting,itwillhelpusinthreeways:1.Theyareakindofassertthatourchangesdon’tbreakthecurrentcode(regressiontests).

2.Wecancheckthebehaviorofthecodewhenitisusedinadifferentway,orwhenanerroroccurs,orevenworkingunderabnormalconditions.

3.Iftestsomepartoftheapplicationbecomesinaveryhardtask,itcouldreflectamistakeindesignandimplementationphases.

Testing… testing everywhere

• Testingstack:• karma(testrunner).• Angulartestingutilities.• jasmine(behaviordrivendevelopmenttestingframework).• protractor(e2etestingframework).

Testing… testing everywhere

• npm test…• Automatically launch abrowser.• The changes inthe code recompileautomatically andtests areexecutedagain.

Testing… testing everywhere

• Wecandebugtheteststoo.

Testing… testing everywhere

• Typeoftesting:• Unittests.• Isolatedtests.• E2E,end-to-end,integrationtests.

MoreQA(QualityAssurance)

• Staticanalyse:linting.• Codecoverage.

Repo

• GitHub:https://github.com/semagarcia• Releases:• WorkshopdemoupdatedtoAngular4.0.0.• Bootstrap&FontAwesome• Addedjson-serverandmockedendpoint• Createdallcomponents• Implementedrouterandroutes• Updatednpmstartscripts• Addedcharacterview• Addedseriesview• Added unit tests

Dudas,preguntas,insultos…