Asynchronous Data Streams In Angular 2 - Jfokus


Asynchronous DataStreams in Angular 2by Gerard Sans (@gerardsans)

A little about meAngular GDE (Google Developer Expert)JavaScript and Angular fanboy Blog @gerardsans activistLooking for Angular Meetup organisersMeetup Group. Follow us!AngularJS Labs (@angularjs labs)

ng-nl 2016 - February 18th@ngnlconf

ng-conf - May 4-6th@ngconf

2 Days: Angular 2 Workshop - April 14-15thJfokus - StockholmTypeScript, Dependency Injection, Template Syntax, Components, RxJS, HTTP, ComponentRouter, Forms, Unit Testing, Migration to Angular 2

AngularConnect - Sept 27-28th@AngularConnect

Asynchronous Data Streams

StreamsAsynchronous, register a callback to benotified when results are availableData, raw information: Number, String,Objects (Arrays, Sets, Maps)Streams, sequences of data madeavailable over time


Streams timelineAlso known aspipes (Unix 3, 1973)streams (Node.js, 2009)async pipes (Angular 2, 2015)Observable sequences, Observables

Functional ProgrammingArray methodsforEach, map, filter and reduceComposition

Array Methodsvar{{{];team [name: "Igor Minar", commits: 159 },name: "Jeff Cross", commits: 84 },name: "Brian Ford", commits: 113 }

forEachfor(var i 0, ii team.length; i ii; i n(member){console.log(;});

mapvar newTeam [];for(var i 0, ii team.length; i ii; i 1){newTeam.push(team[i]);}var onlyNames{return { name: };});

filtervar onlyOver100Commits [];for(var i 0, ii team.length; i ii; i 1){if (team[i].commits 100) {onlyOver100Commits.push(team[i]);}}var onlyOver100Commits team.filter(function(member){return (member.commits 100);});

reducevar total 0; // initial valuefor(var i 0, ii team.length; i ii; i 1){total total team[i].commits;}var total team.reduce(function(total, member){return total member.commits;}, 0); // initial value

eturn}over100Commits(member){(member.commits ;

Key ConceptsObservableOperatorsmerge, concat, map and more!ObserveronNext, onError, onCompletedSubscribe/Unsubscribe

Observable API//Observable constructorlet observable new Observable(observer {try {//pushing ext(3);//finish streamobserver.complete();}catch(e) {//error handlingobserver.error(e);}});

Basic Stream//ASCII Marble Diagram----0----1----2----3---- rx.interval(1000)----0----1----2---- rx.interval(1000).take(3)--- is the timeline0, 1, 2, 3 are emitted valuesX is an error is the 'completed' signalRxMarbles

Basic Stream----0----1----2----3---- rx.interval(1000)----0----1----2---- 00).take(3).subscribe(item console.log(item)); // shows 0, 1, 2

Observerobservable.subscribe(function onNext(value){console.log(value);},function onError(error){console.log(error);},function onCompleted(){console.log('Completed');});var observer new Observer(function onNext(result){console.log(result);},function onError(err){console.log(err);},function le.subscribe(observer);

Unsubscribevar subscriber observable.subscribe(value console.log(value),error console.log(error),() console.log('Completed'));//cleanup handlerssubscriber.unsubscribe();

Arrays vs StreamsArrays (sync)map and filter create new arrayssource must be in memoryStreams (sync/async)only deal with one item at a timeconsume less memorygood for large datasetsvideo

ES6 / TypeScriptES6 (ES2015)- Classes, modules, arrowfunctionsTypeScript- Types, annotations- Better editor support- Angular Team uses it

ES6: OverviewArrow functions and let keyword; Block scopesClasses and inheritance; Default parametersDestructured assignmentGenerators; Iterators; MapsPromises; Rest parameters; SetsSpread operator; Template LiteralsResources- jsbin (ES6/Babel)- Just another introduction to ES6

ES6 modules// ES6importimportimportimportdeconstructing{ member } from "module-name";{ reallyLongMemberName as alias } from "module-name";{ member1 , member2, [.] } from "module-name";defaultMember from "module-name";//------ lib1.js -----export function add(x, y) {return x y;}export function square(x) {return x * x;}//------ lib2.js -----export default function square(x) {return x * x;}//------ main.js -----import { add as sum, square } from 'lib1';import mySquare from 'lib2';sum(1,2); // 3mySquare(2,2); // 4ES6

ES6: Classesclass Person {ES6//class constructorconstructor(name, age) { name;this.age age;}//class methodsayName() {console.log("I'm ";}}function Person(name, age) {//class name;this.age age;}Person.prototype {//class methodsayName: function () {console.log("I'm ";}};let p new Person("John", 25);p.sayName(); // I'm Johnvar p new Person("John", 25);p.sayName(); // I'm JohnES5

ES6: Destructuringlet [one, two] [1, 2];let {three, four} {three: 3, four: 4};ES6console.log(one, two, three, four); // 1 2 3 4ES5var a [1, 2];var one a[0];var two a[1];var b {three: 3, four:var three b.three;var four b.four;4};console.log(one, two, three, four); // 1 2 3 4

ES6: Template literals//multi-linelet text string text line 1string text line 2 ;ES6//interpolationlet p {name: "John", credits: 20};let tpl Name: {}. Credits: {p.credits 10} ;// Name: John. Credits: 30//multi-linevar text "string text line 1\n" "string text line 2";ES5//interpolationvar p {name: "John", credits: 20};var tpl "Name: " ". Credits: " (p.credits 10);// Name: John. Credits: 30

ES6: Arrow functionslet square x x * x;let add (a, b) a b;let pi () 3.1415;ES6var square function(x) { return x * x; }; ES5var add function(a, b) { return a b; };var pi function() { return 3.1415; };

ES6: Default parametersfunction sayMsg(msg 'This is a default message.') {console.log(msg);}sayMsg();sayMsg('This is a different message!');ES6function sayMsg(msg){var msg msg 'This is a default message.';console.log(msg);}sayMsg();sayMsg('This is a different message!');ES5

TypeScript 1.6Basic types: boolean, string, number, anyType annotations and compile-time type checkingType inference, Interfaces, Enumeratedtype, Mixins, Generics, TupleResources- Handbook

TS: Basic typesvar isDone: boolean false;var height: number 6;var name: string "bob";// boolean// number// stringvar list: number[] [1, 2, 3];var list: Array number [1, 2, 3];// arrays// genericsenum Color {Red, Green, Blue};var c: Color Color.Green;// enumsvar notSure: any 4;var list: any[] [1, true, "free"];// if not definedfunction warnUser(): void {alert('WAT?');}// return typeTS


Angular 2 Basic AppWe are going to explore a basic Applicationcovering:BootstrappingComponents, ServicesTemplate syntaxBasic Http Service

BootstrappingAngular Application instantiationRoot componentGlobal DependenciesClasses. Eg: Router, Forms, Http Global ValuesVendor dependencies

Component Treesource: blog

Componentimport {Component} from 'angular2/core';import {FORM DIRECTIVES} from 'angular2/common';import {UsersService} from me', // home /home styles:[ h1 { color: red } ],template: h1 Home /h1 ,directives: [FORM DIRECTIVES],providers:[usersService]})export class Home { . }

Template SyntaxSyntaxBinding type h1 {{title}} /h1 input [value] "firstName" li [] "isActive" /li div [style.width.px] "mySize" InterpolationPropertyClassStyle button (click) "onClick( event)" Event[(ngModel)] "data.value"Two-way

Additional ResourcesAngular 2 website ( (ES5/ES6/TS)


2 Days: Angular 2 Workshop TypeScript, Dependency Injection, Template Syntax, Components, RxJS, HTTP, Component Router, Forms, Unit Testing, Migration to Angular 2. AngularConnect - Sept 27-28th @AngularConnect. Asynchronous Data Streams. Streams Asynchronous, register a callback to be notified when results are available Data, raw information: Number, String, Objects (Arrays, Sets,