+ All Categories
Home > Technology > Angularjs 2x

Angularjs 2x

Date post: 15-Apr-2017
Category:
Upload: saurov-thakur
View: 85 times
Download: 2 times
Share this document with a friend
27
After 2-years of planning finally Ang2 was out in 2016 -RC 1 was out on May, 2016 -RC 2 out on 15 Jun (http://angularjs.blogspot.in/2016/06/rc2-now- available.html) -RC 3 on 22 June ( http://angularjs.blogspot.in/2016/06/rc3-now- available.html) performance issue fixed -RC 4 is out on 1 July,2016 -RC 5 on10 Aug,2016 (http://angularjs.blogspot.in/2016/08/angular-2-rc5- ngmodules-lazy-loading.html) --more releases are comin up as time progresses. For this pressentation I am using RC 4 ses valid HTML DOM element properties and events. ng1 built-in directives(ng-href, ng-src, ng-show, ng-hide, etc.) are no longer re uses href, src, hidden, etc. properties to get the same output. with event based directives(ng-click, ng-blur, etc.) . Modules, jqlite and $scope are gone implemented as class & so DI is injected in constructor as against factory, servi ectives syntax is changed & number reduced. ng-repeat is replaced with *ngFor, et support (Ang1.x dev used Ionic , etc.) ormance (implements webstandards like components) History Saurov Thakur
Transcript
Page 1: Angularjs 2x

After 2-years of planning finally Ang2 was out in 2016-RC 1 was out on May, 2016-RC 2 out on 15 Jun (http://angularjs.blogspot.in/2016/06/rc2-now-available.html)-RC 3 on 22 June ( http://angularjs.blogspot.in/2016/06/rc3-now-available.html) performance issue fixed-RC 4 is out on 1 July,2016-RC 5 on10 Aug,2016 (http://angularjs.blogspot.in/2016/08/angular-2-rc5-ngmodules-lazy-loading.html)

--more releases are comin up as time progresses. For this pressentation I am using RC 4

• Angular 2 uses valid HTML DOM element properties and events. Many of Ang1 built-in directives(ng-href, ng-src, ng-show, ng-hide, etc.) are no longer required.   Angular 2 uses href, src, hidden, etc. properties to get the same output. Same goes with event based directives(ng-click, ng-blur, etc.)

• Controllers. Modules, jqlite and $scope are gone• Service is implemented as class & so DI is injected in constructor as against factory, service, provider, etc.• Builtin Directives syntax is changed & number reduced. ng-repeat is replaced with *ngFor, etc.• Full mobile support (Ang1.x dev used Ionic , etc.)• Better performance (implements webstandards like components)

History

Saurov Thakur

Page 2: Angularjs 2x

Day 1

1. Preparing Environment -Installations & Configurations (Angular2, Typescript, Editor, Server-Lite)2. Introduction to TypeScript & creating the first Ang2 app3. Understanding and Implementing Ang2 - Building blocks (Components, Templates, Decorators/Metadata, Directives[Attribute])4. Practice Session (autoGrow, counter )

Day 2

5. Ang2 - Building Blocks continued (Directives[Structural])6. Styles & Class binding and Pipes7. Data Architecture ( 1-way, 2-way) - One-way binding ( property/attribute binding)8. One-way binding (Event Handlers & Emitters). Passing Input/Output data9. Practice Session ( repeat directive, inventory system)

Day 3

10. 2-way binding : Banana in the box with NgModel11. Forms( Template driven, Hybrid & Model driven/ Reactive)12. Validations(OTB & custom)13. Reactive Programming with Observables using Rx js14. Practice Session

Day 4

15. Ang2 - Building Blocks continued (Services, Dependency injection)16. HTTP (basic)17. HTTP (advanced) - API calls using JSONP (CORS)18. Pipe (Custom) – dealing with Mutability19. Angular Material 20. Practice Session (Stockform, Cascading DropDown )

Day 521. Routing (basic)22. Routing and Navigation (advanced)23. Advanced Concepts - * Lifecycle Hooks, Snapshots, Transclusion, etc.24. WorkShop (applying the concepts learnt)

Page 3: Angularjs 2x

ARCHITECTURE

Building Blocks of Angular 21.Modules2.Components3.Templates4.Metadata5.Data binding6.Directives7.Services8.Dependency injection

We write applications by composing HTML templates with Angularized-markup, writing component classes to manage those templates, adding application logic in services, and handing the top root component to Angular's bootstrapper.

Page 4: Angularjs 2x

• es6-shim – ensure that js runs fine; it is a polyfill & not mandatory for modern browsers• zone.js – detect changes in angular ( like $digest in Ang1)• reflect-metadata -- polyfill that lets us use this metadata(annotations in typescript)• SystemJS – module loader; create modules & resolve dependencies

To run Angular 2, we depend on four libraries:

Bootstrap We Bootstrap module now in rc5 not root component

Page 5: Angularjs 2x

<html> <head> <meta charset=UTF-8> <title>Angular2 Seed</title> <!--<base href="/">--> <!--<script src="node_modules/es6-shim/es6-shim.js"></script>--> <script src="node_modules/zone.js/dist/zone.js"></script> <script src="node_modules/reflect-metadata/Reflect.js"></script> <script src="node_modules/systemjs/dist/system.src.js"></script> <!--Add Stylesheet --> <link rel="stylesheet" type="text/css" href="styles.css">--> </head><body> <!--This tells System.js how to load libraries and files --> <script src="systemjs.config.js"></script> <!-- This tells System.js that we want to load app.js as our main entry point --> <script> System.import('app/app.component.js').then(null, console.error.bind(console)); </script> <hello-world> loading…</hello-world> </body></html>

import {bootstrap} from "@angular/platform-browser-dynamic";import { Component } from '@angular/core';

@Component({ selector: 'hello-world', template: '<h1>Hello World!</h1>'})

class HelloWorld {}

bootstrap(HelloWorld);

project/index.html project/app/app.component.tsTo bootstrap our app to render a root Component (HelloWorld) in the <hello-world></hello-world> snippet of index.html

Page 6: Angularjs 2x

Component : composed of 3 parts –Decorator, View & Controller@Component({ //a function that is decorated with annotations to add metadata.selector: // tells Ang what element to match where the view will be renderedtemplate: //the View; can be inline or url to html can be passed in templateUrl })class MyComponent{ //business rules here. This is the controller} Selectors & their meaningselector: 'StockSearch' // matches <StockSearch></StockSearch>selector: '.stockSearch' // matches <div class="stockSearch">selector: '[stockSearch]' // matches <div stockSearch>we create new elements with components that encapsulate HTML and drop them into our templates as if they were native HTML elements.<!-- Normal HTML --><div>Mental Model</div><!-- Wow! A new element! --><StockSearch></ StockSearch>

Page 7: Angularjs 2x

app\boot.ts (create)import { bootstrap } from "@angular/platform-browser-dynamic";import {AppComponent} from "/app/app.component"; <!—OR, "./app.component"; -->

bootstrap(AppComponent);

app\app.component.ts (change)

import { Component } from '@angular/core';@Component({ <!—All decorators are functions --> selector: 'my-app', template: '<h1>My Angular 2 App</h1>'})<!—“export” ing a class will make it available in other modules and can be used using “import” -->export class AppComponent {}

index.html(change)<script> System.import('app/boot.js').then(null, console.error.bind(console));</script> <my-app></my-app>

The folder structure--project/ app/ app.component.ts boot.ts index.html

Page 8: Angularjs 2x

The Angular Bindings3 categories based on data flow direction

I. Property Binding (1 way Data Binding --> from DataSource to View)

The 'target' can be -

*Element Property<button [disabled]="isUnchanged">Save</button> --- isUnchanged is a Property assigned to button's disabled attribute/property. Similarly,<img [src] = "itemImageUrl"> or <input [value] = “someValue” NgModel>

*Component property(Input to child component)<item-detail [item]="currentItem"></item-detail>

*Directive property<div [ngClass] = "{selected: isSelected}"></div> Technically, Angular matches the name to a property decorated with @Input()Following initializes the prefix property of the ItemDetailComponent to a fixed string. Angular sets it & forgets about it.<item-detail prefix=“I need " [item]="currentItem"></item-detail>The [item] binding, on the other hand, remains a live binding to the component's currentItem property.

{{expression}} Interpolation

[target]="statement" Property, Attribute, Class, Style binding type

**We have a choice bet’n Property Binding & Interpolation

<img src="{{imageUrl}}">interpolated<img [src]="imageUrl">property bound

-both are same

Page 9: Angularjs 2x

II. Event Binding (1 way Data Binding --> from View to DataSource)

The 'event' can be -

*Element Event<button (click) = "onSave()"> Save</button> or <button (keyup)=“showTyping($event)>

*Component event (Output)<item-detail (deleteRequest)="deleteItem()"></item-detail>

*Directive event<div (myClick)="clicked=$event">click me</div>

III. Property & Event Binding (Two way Data Binding)

<input [(ngModel)]=“itemName">

Note: Property Binding is to Pass data from Parent to Child & Event binding for passing data from Child to Parent

(event)="statement" event binding

[(target)]=“expression" event & property binding (banana in the box syntax)

Page 10: Angularjs 2x

Directive : 3 types –

1. Component : directive with a template. Most common.2. Attribute : changes behavior/appearance of element. No template

eg Use case – add highlight on mouseover .3. Structural : change DOM layout by adding/removing DOM elements; eg, NgIf,

NgFor, custom RepeatMe

A component is a directive with a template.So, component rather than adding behaviour to an existing DOM element, actually creates it's own view (hierarchy of DOM elements) with attached behavior.

*Write a component if the need is to create a reusable set of DOM elements of UI with custom behaviour. *Write a directive if the need is to write reusable behaviour to supplement existing DOM elements

2Way binding with two 1-ways binding<input type="text" [value]="isSpecial“ (keyup)="typing($event)"/><span>{{isSpecial}}</span>

typing($event){ this.isSpecial = $event.target.value; }

Page 11: Angularjs 2x

1. Child Directive (called AuthorsListComponent here) - (* eg of counter.component to start with) * prepares for event @Component({ selector: 'authors-list', outputs: ['onAuthorClick:clicks'], //used Alias template: ` <ul> <li *ngFor="let auth of authors" (click)='clicked(auth)'> {{auth}} </li> </ul> ‘

* creates a property of EventEmitter. This property onAuthorClick is exposed to parent as clicks class AuthorsListComponent { onAuthorClick = new EventEmitter<Object>(); }

* Then calls EventEmitter.emit(payload) to fire an event, passing the payload in a message. clicked(obj: Object): void { this.onAuthorClick.emit(obj); }3. Parent directives listen for the event by binding to this property and accessing the payload through the $event object. template: ` <authors-list (clicks)='showAuthor($event)'> </authors-list> ` showAuthor(obj:Object): void { console.log('Author clicked: ', obj); }

EVENT Binding User action may result in flow of data in opposite direction: from element to component<button (click)="onSave()">Save</button> Listens to button’s click eventEVENT Object To capture the event object, pass $event as event parameter. The shape of event object is determined by target, eg, <button (click)="clicked($event)"></button> , a button event , we can do (eg.) clicked(event) { event.preventDefault(); } OR <input [value]=“product.ItemName" (input)=" product. ItemName =$event.target.value" > // 2-way binding-> property & eventvalue is bind to ItemName & any change raises input event handler that sets product. ItemName

CUSTOM Events(EventEmitter)Directive raises custom events with EvenEmitter API. It calls EventEmitter.emit(payload) to fire an event passing a message payload. Parent directives listen for the event by binding to this property and access the payload through $event object.

Page 12: Angularjs 2x

DIRECTIVE* @HostListener is applied to respond to User Action. This is applied to methods which are called when an event is raised.* Directive can be configured with binding to pass parameter and can be called as- [autoGrow]="'200px'" or [autoGrow]="growSize“ //Directive called without parameter- autoGrow* Structural Directive is called using * as- <p *repeatMe="counterValue">{{someValue}}</p>* Parameter passed to directive is captured/decorated as- @Input() autoGrow: string; @Input('autoGrow') autoGrowSize: string; //using AliasOR we can capture in array notation; helpful if more than one parameter is passed inputs: [‘init’] OR inputs: ['counterValue:init'], //using Alias (directive property name on the left and the public alias on the right) outputs: ['counterChange:change'], //using Alias* Paremeter instead of a get(default) can be set also as- @Input() set repeatMe(count: number) { this._viewContainer.clear(); //REFRESHES the display for (var i = 0; i < count; i++) { this._viewContainer.createEmbeddedView(this._templateRef); } }

API's---* TemplateRef : Represents an Embedded Template that can be used to instantiate Embedded Views To instantiate Embedded Views based on a Template, we use ViewContainerRef, which will create the View and attach it to the View Container.* ElementRef : ElementRef allows us to gain access to the native DOM element. It is the location in the View where the Embedded View logically belongs to.

Page 13: Angularjs 2x

template: ` <style>div{color:red;}</style>

<div [style.background-color]="getStyle()"> Hello </div> <button (click)="showStyle = !showStyle;">Toggle </button> <p [class.my-class]="showStyle"> Hello Again</p> <p styled> I am styled by directive </p> `, directives:[StyledDirective], styles: [ ` .my-class { background-color: green; } `]

Applying Styles & Classes * Inline style: creating the style element first and then apply * Style Binding: like property binding * StyleUrl : referencing style filepath * Using a Directive * Class Binding : like property binding * Calling external CSS- in index.html

Page 14: Angularjs 2x

2-way bindingProperty bindings are used to pass data from parent to child, & event bindings pass data from child to parent. Using both we implement 2-way bindings. Eg- display a data property & update that property when user makes changes. <input [value]=“product.ItemName" (input)=" product. ItemName =$event.target.value" >

Instead of remembering element property (value) and event(input), we usengModel - sets the property value & ngModelChange - listens to change for element’s value are used<input [ngModel]="todo.text" (ngModelChange)="todo.text=$event">But this is too verbose. So we use an easy common pattern- ’banana in the box syntax ’.<input [(ngModel)]="todo.text"></input> [()] only sets data-bound property; to do something else at property change we still need to use ngChangeModel.<input [ngModel]="todo.text" (ngModelChange)=“toUppercase($event)">

Referencing a Template variable - For two components to talk to each other we can define references<video-player #player></video-player> <button (click)="player.pause()">Pause</button>If there is a component on the element, the variable refers to the component instance. If there is no component on the element, the variable refers to the element itself.<input #i{{i.value}}

Visibility with NgIf

0templateform.component

Page 15: Angularjs 2x

FORMS

Angular has 3 different ways of building forms --1. Template-driven - allows to build forms with very little to none application code required2. Model-driven or reactive  - uses low level APIs that makes forms testable without a DOM being required3. Hybrid/Partial Model-driven - kind of model-driven but with a higher level API called the FormBuilder

For all forms we need atleast two-way data binding, change tracking, validation, and error handling ... 

Page 16: Angularjs 2x
Page 17: Angularjs 2x

TYPE1: Template-Driven FORMS

<form (ngSubmit)="onSubmit(theForm.value)" #theForm="ngForm"> <label for="movieName">Movie Name</label> <input type="text" [(ngModel)]="modelMovie.movieName" required/> <button>Submit</button></form>All forms have the directives ngForm applied by default(invisible). It provides State, JSON form Value, Validity, etc info.

Put cursor in the input and then outside, then edit input-content, then MT it..and see how classes changes to reflect the control’s state. We can decorate these classes to apply color to indicate the state(green-ok, red-error,etc.). (0templateform & 0.5templateform)

*Note : The output(form object) is MT object. Because there’s nothing in the template to tell the form that the input controls are part of this form. We need to register form controls on ngForm instance using directive ngControl as- <input type="text" [(ngModel)]="modelMovie.movieName" required ngControl=“mName”/>

Instead of simple JSON – { mName:’bla bla’, rating:5 } if we need data as { movieInfo: { mName:’bla bla’, dirName:’rrr’ }, movieStats:{rating: 4 , relYear:”1999”, budget:’40k’} } We apply ngControlGroup as --->1templateform

State Class if true Class if falseControl has been visited ng-touched ng-untouchedControl's value has changed ng-dirty ng-pristineControl's value is valid ng-valid ng-invalid

onSubmit(value:any) { console.log(value); } //MT Object

onSubmit(value:any) { console.log(value); } //Object {mName: “Bla bla "}

<div ngControlGroup=" movieInfo "> <input type="text" ngControl=" mName"> <input type="text" ngControl=" mName "> </div> <div ngControlGroup="address"> <input type="text" id=“fname" ngControl=" fname "> <input type="text" ngControl=" dob "> <input type="text" ngControl=" addess "> </div>

Page 18: Angularjs 2x

Validations & Error Message

<form (ngSubmit)="onSubmit(theForm.value)" #theForm="ngForm"> <fieldset ngControlGroup="info"> <label for="movieName">Movie Name</label> <input type="text" [(ngModel)]="modelMovie.movieName" placeholder="Enter Name" id="movName" ngControl="movName" #mName="ngForm" required minlength="3" maxlength="15" /> //Notice the ref var to ngForm that is tracking the state of our data. Also how Vadiation is set <span [ngClass] = "{'has-error': mName.touched && !mName.valid}" //applying class to color the error *ngIf="mName.touched && mName.errors"> //check for error <span *ngIf="mName.errors.required">Enter Movie Name</span> <span *ngIf="mName.errors.minlength">Min 3 chars</span> <span *ngIf="mName.errors.maxlength">Max 15 chars</span> </span> <label for="directorName">Director Name</label> <input type="text" [(ngModel)]="modelMovie.directorName" id="dirName" ngControl="dirName" required /> </fieldset> <fieldset ngControlGroup="stats"> <label for="releaseYear">Release Year</label> <input type="text" [(ngModel)]="modelMovie.releaseYear" id="relYear" ngControl="relYear" required/> …… </fieldset> http://blog.angular-university.io/introduction-to-angular-2-forms-template-driven-vs-model-driven/

Page 19: Angularjs 2x

Type 2: Partial Model-Driven FORMS

From previous, we saw that Forms are made of Controls & ControlGroups. Building Controls/ControlGroups implicitly using ngForm and ngControl is convenient, but doesn’t give us a lot of customization options. A more flexible way is to configure forms using a FormBuilder (API) by injecting in the class constructor. And create Control & Controlgroups. Also we create Validations using the static methods of Validation class.Once done we have to group it in a property and pass the property to the form template.Form group expect (key:value) pair where key->name of the control & value->actual instance of the control

To tell Angular that we are controlling the form from the model we use [ngFormModel] directive and assign the group property set in the component class.

*Note : - In this Model we set data at the template & not on the model so the first parameter of the Validator, which should be the default control value, is null.- No more referece variable is required to refer to the control- Error messages in template remain same. Just remember that 3 form field states are tracked by Angular & below CSS are applied to both form & its controls-touched & untouched, valid & invalid, dirty & pristine

Page 20: Angularjs 2x

Partial Model with ngFormModel & FormBuilder

<form [ngFormModel]="myForm" (ngSubmit)='saveData(myForm.value)'> //”myFrom” is pushed from Model/Component class. <label>Movie Name:</label> <input type="text" id="movName" ngControl="movName" > //Value can be set as – [ngModel]="modelMovie.movieName <div *ngIf="!movName.valid">Movie name is reqd</div> //Validation Error Mesg remains same …..<button type="submit">Submit</button></form> //No more to use the template reference variable like #variableclass Form2Component {//CREATE ControlsmyForm: ControlGroup;movName: Control; dirName: Control;//INJECT FormBuilderconstructor(private fb:FormBuilder) { this.movName = new Control('', Validators.required) //1st para, control’s default value is null as DataBinding for PartialModel happens in Template this.dirName = new Control('', Validators.compose([Validators.required, Validators.minLength(3)])) //For multiple validators we need to compose

//CREATE Group to Pass to Templatethis.myForm = fb.group({ //myForm is pushed to Form template //'movName': this.movName, movName: this.movName, //Cannot be mname:this.movName as this is (key,value) pair dirName: this.dirName });} 2templateForm

Page 21: Angularjs 2x

Type 3: Model-Driven/Reactive FORMS

Here all are in class. This makes code more testable & more business logic even can be applied to Validation too. We will use the new forms module '@angular/forms‘. Bootstrap this –import { provideForms } from '@angular/forms'; (Ang forms does not live in common barrels(system-config.js) anymore and comes with ang/forms)bootstrap(AppComponent,[…, provideForms() ]) //this enables new form module

We still use FormBuilder to create Controls/ControlGroups or rather, the new, FormControls/FormGroup A form is a type of FormGroup. A FormGroup can contain another FormGroup or FormControl

As earlier, template has the input elements we define the bindings but with [formGroup] & formControlName

REACTIVE : LISTEN TO FORM AND CONTROLS CHANGESWe can listen to form control changes using Observable. Each form group or form control expose a few events which we can subscribe to (e.g. statusChanges, valuesChanges, etc). Then we can check for for the state and apply validation.

Here we set the defaut element values in class(Validators) and instead of constructor we use OnInit interface to call any API to fetch data.

Page 22: Angularjs 2x

Model/Reactive formimport { REACTIVE_FORM_DIRECTIVES, Validators, FormGroup, FormControl, FormBuilder } from '@angular/forms';directives: [REACTIVE_FORM_DIRECTIVES]<form [formGroup]="myForm"> <label>Movie Name</label> <input formControlName="movName"> <div *ngIf="formError"> {{formError}}</div> //or <p *ngIf="myForm.controls.movName.errors">This field is required!</p><button type="submit">Submit</button>

class ModelComponent implements OnInit{ constructor(private fb: FormBuilder) {} myForm: FormGroup; formError:string = “”; //public var to set the error message

this.myForm = this.fb.group({ movName : ['callAPI&setValue',[Validators.required, Validators.minLength(5)]] });//Listen to form change this.myForm.valueChanges.subscribe(value => { console.log(value); this.onValueChanged(value); });//apply the Error message onValueChanged(data:any){ this.formError =''; //to check field state (valid, or pristine etc., we need to get the value from myForm controls, e.g. myForm.controls.name.valid. let hasError = this.myForm.controls[‘movName’].dirty && !this.myForm.controls[‘movName’].valid; if(hasError){this.formError = ‘Movie name is required'; }}

Page 23: Angularjs 2x

Custom Validation

//Write Component class defining the Validationimport {Control} from '@angular/common';export class CustomValidators{ //A number with 6 digits static zipCodeValidator(control) { var valid = /^\d{6}$/.test(control.value); return !valid ? { invalidZip: true }: null; }}

The FormComponent where it is appliedclass FormComponent {zipcode: Control; constructor(private fb:FormBuilder) { this.zipcode = new Control('',Validators.compose([Validators.required, CustomValidators.zipCodeValidator])); …… }

The Template<input id="zipcodeInput" type="text" placeholder="zip is 6 digits" ngControl="zipcode"><em *ngIf="zipcode?.hasError('invalidZip')">Must be 6 digits </em>

Page 24: Angularjs 2x

Reactive Programming – Everything is (events/actions) a stream. Mouseclick; Button press; Http request – all is a stream.Combine, Modify and Suscribe to these events(streams) is what is in reactive programming paradigm.

Stream emit 3 things :1. a value(of sometype)2. an error3. a completed signal

We listen & react to a stream. Listening is called Subscribing & the streams are called Observables. We capture these events asynchrously by defining functions for each emitted things.

(In Angular 2, we can get Observables by sending HTTP requests, or using the Control API)

We Subscribe to observables with .subscribe function that executes the observable. It has three callback parameters : .subscribe(success, failure, complete);eg:.subscribe( function(response) { console.log("Success Response" + response)}, //we can take the results from the success callback and assign it to a variable,etc. function(error) { console.log("Error happened" + error)}, function() { console.log("the subscription is completed")});

In Reactive libraries, each stream has many functions, such as map, filter, scan, etc. When one of these functions are called, eg, clickStream.map(f), it returns a new stream based on the click stream. It does not modify the original click stream in any way. This is a property called immutability that allows to chain functions, clickStream.map(f).scan(g).

.map() is a transformer that will transform the result to whatever you return (in your case .json() or any custom object) before it's passed to the success callback you should called it once on either one of them.The map operator works on streams. That is, it runs the function once for each item in the stream and emits the return value of the function.All the Angular http request returns an Observable<Response> which we can subscribe & unpack the objects therein(as JSON, etc.)

Page 25: Angularjs 2x

HTTP vs JSONP API for WIKI SEARCH - http://en.wikipedia.org/w/api.php?callback=JSONP_CALLBACKDetails on - https://www.mediawiki.org/wiki/API:Opensearch

Trying the API with http.get() I got the error – “XMLHttpRequest cannot load https://en.wikipedia.org/w/api.php?action=opensearch&search=se&format=json. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.”

We have a Cross-Origin (CORS) issue here and the API didn’t accept my request.I was doing an XMLHttpRequest to a different domain than my page is on(localhost). So the browser is blocking it as it usually allows a request in the same origin for security reasons.

Enters JSONP (JSON with padding), a communication technique to request data from a server in a different domainAngularJS http service has a built-in method called "jsonp” for the purpose.

https://premaseem.wordpress.com/2015/01/22/using-jsonp-with-angularjs/

I did the eg in keypress event which is not very smart -Taming the user inputLet’s change our code to not hammer the endpoint with every keystroke but instead only send a request when the user stopped typing for 400 ms. This is where Observables really shine. The Reactive Extensions (Rx) offer a broad range of operators that let us alter the behavior of Observables and create new Observables with the desired semantics.http://blog.thoughtram.io/angular/2016/01/06/taking-advantage-of-observables-in-angular2.html

Page 26: Angularjs 2x

Builtin Pipe | Parameterizing Pipe | Chaining Pipe | CUSTOM Pipe

Pipes and Change DetectionAngular looks for changes to data-bound values through a change detection process that runs after every JavaScript event: every keystroke, mouse move, timer tick, and server response. This could be expensive. Angular strives to lower the cost whenever possible and appropriate.Angular picks a simpler, faster change detection algorithm when we use a pipe.

The pipe class implements the PipeTransform interface's transform method that accepts an input value followed by optional parameters and returns the transformed value.To create your own(Custom) pipe you need to decorate a basic class with the new @Pipedecorator and conform to the PipeTransform interface of transform(value:number, args:string[]) : any

Pipes Immutability If we mutate the array, no pipe is invoked and no display updated; if we replace the array, then the pipe executes and the display is updated

Pipe expects a new reference to comein to transform method it wil not see any array change like adding or removing arrary item.So immutability comes in... We use sread operator and create a new array and append a new element

Pure /Impure (Async, Json) PipeThere are two categories of pipes: pure and impure.Angular executes a pure pipe only when it detects a pure change to the input value. A pure change is either a change to a primitive input value (String, Number, Boolean, Symbol) or a changed object reference (Date, Array, Function, Object).Angular executes an impure pipe during every component change detection cycle. An impure pipe will be called a lot, as often as every keystroke or mouse-move.(http://stackoverflow.com/questions/37575952/angularjs2-losing-binding-after-pipe-filter)

Page 27: Angularjs 2x

?


Recommended