TypeScript and Angular workshop

85
GUL-UC3M TypeScript & Angular Workshop 30 de Marzo de 2017 Isabel Matas Rabadán & José Manuel García García

Transcript of TypeScript and Angular workshop

Page 1: TypeScript and Angular workshop

GUL-UC3M

TypeScript& AngularWorkshop

30 de Marzo de 2017

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

Page 2: TypeScript and Angular workshop

GUL-UC3M

TypeScript& AngularWorkshop

30 de Marzo de 2017

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

Page 3: TypeScript and Angular workshop

Whoarewe?

IsabelMatasBecArquitecta JavaScript

Sema GarcíaArquitecto JavaScript

Page 4: TypeScript and Angular workshop

Disclaimer

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

Page 5: TypeScript and Angular workshop

Agenda

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

Page 6: TypeScript and Angular workshop

TypeScript

Page 7: TypeScript and Angular workshop

TypeScript

Page 8: TypeScript and Angular workshop

IntroductiontoTypeScript

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

Page 9: TypeScript and Angular workshop

IntroductiontoTypeScriptTYPESCR IPT… WHO ARE YOU?

Shedding light on JavaScript to whom have lost hope…

Page 10: TypeScript and Angular workshop

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…

Page 11: TypeScript and Angular workshop

IntroductiontoTypeScript

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

Page 12: TypeScript and Angular workshop

IntroductiontoTypeScript

…Tell us what we cando…

Page 13: TypeScript and Angular workshop

IntroductiontoTypeScript

…Help us when we’ve forgot something…

Page 14: TypeScript and Angular workshop

IntroductiontoTypeScript

Page 15: TypeScript and Angular workshop

IntroductiontoTypeScript• TypeScript willalwaystranspile toJavaScript,evenwhentherearewarnings.

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

• ATypeScript projecthastohaveafilecalledtsconfig.json initsrootpathfolder.

Page 16: TypeScript and Angular workshop

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.

Page 17: TypeScript and Angular workshop

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

• Toreducetheboilerplate,theconstructorparams areconsiderasattributestoo:

• Itwillbevalidwhilethevariablespassedasargumentssatisfyitsstructure…

Page 18: TypeScript and Angular workshop

IntroductiontoTypeScript• Writingclasses,interfacesandobjecttypes.

• Aninterfacecanbeconsiderlikeaobjecttype,becauseguaranteeitsstructure.

• Ifaclassdoesnotsatisfytheinterfacestructure,itwillthrowanerror…

Page 19: TypeScript and Angular workshop

IntroductiontoTypeScript• Writingasubclass(inheritance)thatimplementsaninterface

(“d”avoidsthecompilationerror)

Page 20: TypeScript and Angular workshop

IntroductiontoTypeScript• Writinganunionandtypeguards.

• Howcancontrolthissituation?

!!

"

Page 21: TypeScript and Angular workshop

IntroductiontoTypeScript

• TypeScript supportsgettersandsetters asawayofinterceptingaccessestoamemberofanobject.Thisgiveusawayofhavingfiner-grainedcontroloverhowamemberisaccessedoneachobject.

Page 22: TypeScript and Angular workshop

IntroductiontoTypeScript• TypeScript alsoallowustodefinestaticproperties/methodsbesidesinstanceproperties/methods.

• Wecanuseitdirectlywithoutaninstance:

• Andalsowecancreateinstancefromit:

Page 23: TypeScript and Angular workshop

IntroductiontoTypeScript

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

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

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

• Readonly:propertiesmarkedasreadonlymustbeinitializedattheirdeclarationorintheconstructor.Laterwillbenotpossible.

Page 24: TypeScript and Angular workshop

Who comesfrom AngularJS?

Page 25: TypeScript and Angular workshop

Angular… WTHis that?

• Fromframeworktoplatform

DependencyInjection Decorators Zones

Compile Change Render

Material Mobile Universal

CLI LanguageServices Augury

ngUpgrade

Router

Animation

i18n

Page 26: TypeScript and Angular workshop

Angular… WTHis that?

• FullDevelopmentStack

Page 27: TypeScript and Angular workshop

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

Page 28: TypeScript and Angular workshop

Thesuper-tooltotherescue:AngularCLI

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

Page 29: TypeScript and Angular workshop

The7magnificent

Modules

Components

Templates

Databinding

Structuraldirectives

Services

DependencyInjection

Page 30: TypeScript and Angular workshop

Createanewproject

ng new project-name –style=scss

Page 31: TypeScript and Angular workshop

Createanewproject

Page 32: TypeScript and Angular workshop

Whatthingstherearehere?

Link

index.html

bundle.js

Link references

styles.(s)css

styles

references

src

Page 33: TypeScript and Angular workshop

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

Page 34: TypeScript and Angular workshop

Applicationbootstrapping

• Allapphas,atleast,onemodule:therootone

Page 35: TypeScript and Angular workshop

Applicationbootstrapping

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

Page 36: TypeScript and Angular workshop

Applicationbootstrapping

Declarations:• Whichcomponentswillbelongtothatmodule.• Theonlydeclarableelementsallowedherearecomponents,pipesanddirectives.

Page 37: TypeScript and Angular workshop

Applicationbootstrapping

Imports:

• Thedeclarationofwhichothermodulesthecurrentmoduleneeds.• WecanimporteithercoreAngularmodulesorourones.

Page 38: TypeScript and Angular workshop

Applicationbootstrapping

Imports:• Usually,wewillonlyhaveonebootstrappedcomponent.• Thisbootstrapprocessdefinesthecomponentsthatareinstantiated.

Page 39: TypeScript and Angular workshop

Applicationbootstrapping

Rootcomponent

Page 40: TypeScript and Angular workshop

ModulesandAppModule

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

Page 41: TypeScript and Angular workshop

AppComponentComponenttree.

Page 42: TypeScript and Angular workshop

AppComponent

Page 43: TypeScript and Angular workshop

AppComponent

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

Page 44: TypeScript and Angular workshop

ComponentsandWebComponents

Page 45: TypeScript and Angular workshop

Components

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

Page 46: TypeScript and Angular workshop
Page 47: TypeScript and Angular workshop

Bindings

• Waystodatabind

Page 48: TypeScript and Angular workshop

Addinganothercomponent

ng g component XXX

Page 49: TypeScript and Angular workshop

Allourcomponents

• AppComponent• HomeComponent• SeriesComponent• CharacterComponent

Page 50: TypeScript and Angular workshop

AngularServices

Page 51: TypeScript and Angular workshop

Services

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

Page 52: TypeScript and Angular workshop

Addingaservice

ng g service XXX

Page 53: TypeScript and Angular workshop

Metadataforaservice

• Add@Injectable() decorator:

Page 54: TypeScript and Angular workshop

Registeringaservice

• Addittoproviders entrypropertyinamodule:

Page 55: TypeScript and Angular workshop

Usingaservice

• Importtheservice.• Addthedependencytotheconstructorofcallerclass:

Page 56: TypeScript and Angular workshop

Usingcoreservices

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

Page 57: TypeScript and Angular workshop
Page 58: TypeScript and Angular workshop

Navigating/AngularRouter

• Appcomposedbydifferentcomponents/views

Page 59: TypeScript and Angular workshop

Navigating/Router

• Definingroutes

Page 60: TypeScript and Angular workshop

Navigating/Router

• Wherewillberenderedmycomponents?

Page 61: TypeScript and Angular workshop

Navigating/Router

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

Page 62: TypeScript and Angular workshop

RouterModule

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

Page 63: TypeScript and Angular workshop

Navigating/Router

• Toaccess toURLparams we cando:

• Inject the service.• Onceinjected the service:

Page 64: TypeScript and Angular workshop

Callingtobackend

Page 65: TypeScript and Angular workshop

Callingtobackend

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

Page 66: TypeScript and Angular workshop

Callingtobackend

• Afterthat,insidetheservice,theimplementation:

Remember:AsweareusingTypeScript,weshouldspecifythereturntypeofthefunction.

Page 67: TypeScript and Angular workshop

Callingtobackend

• But,thatobservable… How canIuseit?

• Ofcourse,we canchain moreRx operators:

Page 68: TypeScript and Angular workshop

Observables:thereactiveway

Page 69: TypeScript and Angular workshop

Observablesinareactiveworld

• Reactiveprogrammingisprogrammingwithasynchronousdatastreams:eventbusesortypicalclickeventsarereallyanasync eventstream,onwhichwecanobserveanddostuff.

Page 70: TypeScript and Angular workshop

Observableexample

• Grayboxesarefunctionsthattransformsonestreamintoanother.

• First,weaccumulateclicksinlists,whenever250msofsilencehashappened(throttle).

• Thisresultisastreamoflists,fromwhichweapplyotheroperationtomapeachlisttoanintegermatchingitslength.

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

Page 71: TypeScript and Angular workshop

Observableorpromise?

• Whyobservablesarebetterthanpromises?

Promises

• Handlesasingleeventwhenanasync operationcompletesorfails

• Returnsasinglevalue• SupportedinES6

Observables

• Handlesastream(zeroormorethanzeroevents)

• Offersthefeaturesprovidedbypromisesandmore

• Theyarecancellable• Theyhaveusefuloperatorslikemap,reduce,retry...

Page 72: TypeScript and Angular workshop

Observableorpromise?

Pipes:transformingdata

Page 73: TypeScript and Angular workshop

Addingapipe

ng g pipe XXX

Page 74: TypeScript and Angular workshop

Pipes

• Thepurposeofapipeistotransformdisplayedvalueswithinatemplate.• Oneadvantageofpipesconsistofawaytowritedisplay-valuestransformationsthatwecandeclareinHTMLtemplates,insideoftheinterpolationexpression.

Page 75: TypeScript and Angular workshop

Pipes

• Thepipescanbeparameterized:

• Thepipesalsocanbechained:

Page 76: TypeScript and Angular workshop

Pipes

• Imagineyouwanttocountthelengthofastringtooutputittotheuser.• Apipecanbetheperfectsolution,becauseitcanbereusedanywherewithoutbecoupledtoacomponent.

Page 77: TypeScript and Angular workshop
Page 78: TypeScript and Angular workshop

Testing… testing everywhere

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

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

2.Wecancheckthebehaviorofthecodewhenitisusedinadifferentway,orwhenanerroroccurs,orevenworkingunderabnormalconditions.

3.Iftestsomepartoftheapplicationbecomesinaveryhardtask,itcouldreflectamistakeindesignandimplementationphases.

Page 79: TypeScript and Angular workshop

Testing… testing everywhere

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

Page 80: TypeScript and Angular workshop

Testing… testing everywhere

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

Page 81: TypeScript and Angular workshop

Testing… testing everywhere

• Wecandebugtheteststoo.

Page 82: TypeScript and Angular workshop

Testing… testing everywhere

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

Page 83: TypeScript and Angular workshop

MoreQA(QualityAssurance)

• Staticanalyse:linting.• Codecoverage.

Page 84: TypeScript and Angular workshop

Repo

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

Page 85: TypeScript and Angular workshop

Dudas,preguntas,insultos…