Angular 2 and Observablesfiles.meetup.com/19844279/Angular-2-talk-from-2016-10-17.pdf · The Wonder...
Transcript of Angular 2 and Observablesfiles.meetup.com/19844279/Angular-2-talk-from-2016-10-17.pdf · The Wonder...
Angular2andObservables
TheZanandJaynaofReactiveComponentDevelopment
Justincaseyoudon'tknow...
TheWonderTwinsofAngular2are
Components
RxJSObservables
TheygotogetherlikeChocolateandPeanutButter
He'sCorny,WhoisThisGuy?
KenRimple-DirectorofTraining,ChariotSolutions
Long-timeJavaguy,Spring,nowintoJavaScript...TeachingandconsultingatChariotfor9+yearsAuthorofvariousAngularJScoursesatChariotCo-authorofAngular2andReactcoursesatChariotFatherof4andinveteratebadpunster
Wheretofindme
Onthetweeterat@krimpleChariotTechCast/DevNewspodcasthostWritearticlesatchariotsolutions.com/blogaboutJSframeworksandmore
Angular2is
AComponent-basedJavaScriptFramework...girdedbyaFunctionalReactiveAPI,Microsoft'sRxJS5.0
WhatisaComponent?
@Component({ selector: 'message-area', template: `... html content here`, ...})export class MessageAreaComponent { constructor() { } message: string; // state variables doSomething() { ... } // user-defined methods ngOnInit() { ... } // lifecycle methods}
You'reneverwalkingalone...
Theapplicationisbootstrappedwithanoutercomponent
Acomponentinusebyanoutercomponent
// in the template of the outer component...
<message-area messageText="Don't walk and chew gum" [messageOptions]="messageOpts" (messageAccepted)="clearMessageText()"></message-area>
We'lllookateachoftheseassignments...
Staticassignment
messageText="Don't walk and chew gum"enabled="true"
UsesthepropertyName="value"syntax,andexpectsliteralvaluesUsedforsimpleoptions
Propertybinding
[propertyName]="variableOrExpression"
LooksinthecurrentcomponentforamembervariableorevaluatesanexpressionThevalueisassignedbyreferencetothepropertypropertyNameintheinnercomponent
EventBinding
(eventName)="methodCall()"
Whenthemessage-areacomponentemitsthenamedevent,executethemethodmethodCall()intheoutercomponent
DifferencesfromAngularJs1.x?
(Tons)
Nomore$scope,controllerStillhaveServices,thoughcreateddifferentlyStillhave"filters"butthey'recalledPipesnowDependenciesinjectedviaconstructorinjectionTypeScriptclassesinsteadofplainES5TheoldmessagebusisreplacedbyRxJSPromisesnowuseES2015PromisesyntaxorarereplacedbyRxJSobservables
ComponentDemos
ComponentsandObservables
WhatisanObservable?
AnabstractioninRxJSthatcanactasadatastreamemitstypedinformationnotifiessubscriberswhentheinformationchanges
Thisisafunctional,reactiveframework,
enabledbyComponentsandRxJS...
Observablescanbeoperatedonfunctionally
ComposestreamsofobservableeventsChainoneoperatortoanotherTransformthestreamtowhatyouwantAllowformorethanonesubscriber
KeyObservableType-EventEmitter
UsedinUItoreporteventsfromonecomponenttoanotherBoundusingthe@Outputannotation
@Component({ ...})export class ReportingComponent { @Output() onStatusChanged: EventEmitter<string> = new EventEmitter<string>();}
Emittinganevent
@Component({ ... template: ` <button (click)='emitEvent()'>go!</button> `})...export class ReportingComponent { ... emitEvent() { this.onStatusChanged.emit('OUCH!'); }}
Acceptinganemittedevent
Inject@Inputparametersusingeventsyntaxandsubscribeinyourcode
in template:<reporting (onStatusChanged)= "addStatusToHistory($event)"></reporting>
Demo-emittinganeventfromaninput
field
HttpAPIinAngular1.x-PromiseBased
// fetching data - APIreturn http.get('/api/customers') .then( (response) => { return response.data; } });
// callerservice.getData() .then((data) { this.data = data; });
Angular2HttpAPIusesObservables
// fetching data - service return http.get('/api/customers') .map((res) => { res.json() })
// fetching data - callerservice.getData().subscribe( (results) => { this.results = results; } (error) => { ... });
ObservableupdatesforHttp
// updateshttp.post('/api/customers', {}) .then( () => { /* leave location */ }, (error) => { /* show error */ });
Demo-REST
KeyObservableType-Subject
ActsasanObservableandanObserverMeaningyoucanuseittoemiteventsinastreamNottiedtoanUIcomponent
// creating - stream of arrays of stringslet dataStream = new Subject<string[]>();
// emitting - send an array chunkdataStream.next(['b', 'c', 'asdfkalsjdf']);
// subscribingdataStream.subscribe( (payload) => { console.log(payload); }, (error) => { alert('error with stream');}, () => { console.log('stream closed'); });
PotentialSubjectStrategies
UseasanadaptertotranslatedatafromanotherAPIMidiInputUser-definedevents
GreattodecouplesourcesandsinksofdataDataissentasynchronouslyAngularusesthisinternallyExampleinRxJS-Observable.webSocket
Demo-SynthesizerinAngularandRxJS
AdvancedFeaturesofObservables-Operators
Observablestreamscanbecomposedandoperatedonwith
Higher-orderfunctionslikemap,debounce,filter,etc..Dozensbuilt-intoRxJS5.0-see forexamples
ObservableAPI
Excellentreference
Summary
Angular2isPowerful
ButyouneedtolearnObservablestomakeitreactiveYouneedtomasterComponentsand@Inputand@OutputtocommunicateLookateachAngularAPIandlearnhowtheObservablesareused
ResourcesandQ&ALookonTwitterat fortheslidedeckandcodesampleslatertonightChariot'sAngularandReacttrainingcourses,aswellasScala
Ken'sblogarticlesaboutAngular,aswellasthosefromotherCharioteersonScala,React,Mobileandmore-
WehaveaPhillyETEvideowatchingpartycomingup-
@krimple
chariotsolutions.com/training
chariotsolutions.com/blog
chariotsolutions.com/events