Skip to content

Angular Tutorial

What is Angular

Angular is a framework to develop Single Page Applications, based on TypeScript. It is developed by the Angular Team in Google, and was launched in 2016 with a stable version 2. It is a complete rewrite of AngularJS, another framework developed by Google.

Angular use common features from server side frameworks, such as Modules, Dependency Injection, a typed language, and recommends a folder-by-feature structure, making several decisions for you, including design and architectural decisions. This things makes a bit harder to enter to Angular development, and you may find you self looking for the Angular way when doing the most simple thing. But they also allows a easy scaling of the application, and a consistent development in a large team of developers.

Single page application architecture

Every application have its own architecture, but there are certain parts that all single page applications would eventually need.

  • User Interface Layer
  • HTTP library
  • Logic
  • Router
  • State manager

This are, somehow, the most common pieces that you would need to build a complete SPA.ref

Another way to look at a SPA architecture can be through layers: ref

  • View
  • Services
  • Store
  • Domain

You can see the relation between both approaches.

What makes Angular a framework?

If you take a look a the architecture, you will notice that Angular actually have a module, or library, for each part of the architecture.

This is what makes Angular a framework, the fact that it is composed by several modules that fills the needs to develop a Single Page Application.

In comparison with React, or Vue, they only represents the View part of the architecture, or the User Interface, leaving you on your own to choose the best library for the another layers of the application.

  • Components for the User Interface Layer
  • HttpClient as the HTTP library
  • Component and Services for the Logic
  • Router for the Routing
  • Services as State manager

Additionally you have other libraries to help you in the development of the application, such as:

  • Animations for javascript animations
  • Forms for template driven forms
  • ReactiveForms for model driven forms
  • i18n for internalization, and localization
  • Pipes for template data transformations
  • Platform modules for different target platforms (eg: Browser, Webworker)
  • Guards for authentication and authorization management
  • CLI tool for fast setup, testing and build
  • Many more...

Learning Angular

Angular have a s shaped learning curve, meaning that you probably will start really slow, as you need to learn how to use several tools aside from the framework itself that is actually quite large and full of features. You will need some time to have experience with it, but after that, you probably wont need to learn anything else.

To start with Angular, there are several technologies that may afraid you at first:

  • Typescript
  • ES2015 (and ES2016, ES2017, ES2018)
  • Decorators
  • Observables
  • rxjs
  • Lazy Loading
  • AOT
  • Dependency Injection
  • And list goes on...

It's totally normal to feel afraid by those, I mean... What the heck Angular? Why can't you just be normal?

And... the Angular Style Guide.

This design choices are valuable when developing a large application, but they will benefit you even in a small application.

If you want a complete introduction to the Angular world, the Tour of Heroes tutorial is the place to go. It is constantly updated, and will have the most used feature covered in a really step-by-step explanation.

Now I will give a small introduction of the most important, and most controversial tools used by Angular.

Typescript

This is the most common argument against Angular, and actually you can develop an Angular application without using Typescript. But, here is why you probably will better with it:

  • Automatic Dependency Injection
  • Advantages of ES2015+
  • Decorators
  • IDE-like experience

ES2015+

Some of us are still using plain ES5 to develop an application. Well, almost ES5, as we always are using something on top of it, as lodash, jquery, and other things. But build tools, as Webpack or Rollup, are now quite common, and you should not be uncomfortable using them. Using features of ES2015+, you probably won't even need jQuery or lodash.

Decorators

The decorator pattern is a design pattern that allows behavior to be added to an individual object, either statically or dynamically, without affecting the behavior of other objects from the same class.ref In Javascript, Decorator proposal was in Stage 1 when Angular Team announce they will be using decorators in ATScript, a short lived language that extends Typescript. Microsoft accepted to introduce many of ATScript features in Typescript, to be used by the Angular Team in the development of Angular 2. It is now in Stage 2, but its specification have change. Typescript still use the previous specification, as it is used by Angular.

The most important thing to understand about Decorators, is that at the end, they are only functions, that add a behavior in a class, property or method. They are really easy to use, to learn, and to develop. If you are have a React background, you can think they are some kind of high order function.

Observables (Reactive Programming and rxjs)

This actually should be the harder thing to learn, but one of the things that you won't live without afterward. Reactive programming is a programming paradigm to deal with data in an asynchronous fashion, that allows to get the last value of a computed operation. Reactive programming implementation in Javascript are going to be Observables currently are on Stage 1, soon to be on Stage 2. This means that in a couple of years, probably, all major evergreen browsers will support this natively.

rxjs is a library that implements its own version of the Observable, and it's used heavily by Angular, specially to deal with data fetching as HttpClient instance will return an observable, and to emit events, as EventEmitter extends from Observable.

To make your learning path easy, every instance of rxjs Observable have a toPromise method, to resolve the value of the observable as a promise after it completes. This is tricky when you are dealing with user events, as most of then will never complete, but you can use this approach to deal with data fetching, as they will be complete after the request. Still it's better to understand rxjs observables, and how to use its operators.

Lazy loading, AoT, Dependency Injection... And the Angular Style Guide.

Dependency injection is something that you should need to know when developing with Angular, but this is somewhat common in other frameworks, specially in server side frameworks. Still, if you don't know what dependency injection is, very quickly, is the ability to ask for an instance of a class, and have it. This a really simple way to see it, but at the end, that's actually what it is.

For everything else, you have MasterCard. Ok, you may not. But don't need to know all this things. Sure, lazy loading and AoT will help you to reduce the bundle size of the application, but first, build that application. It's easy to add up those things afterward, and they are not needed to start developing.

About the Angular Style Guide, well, that's something I like about Angular, they have it's own way to do things. When you have time, give it a look. Sure it will help you when dealing with a large application.

ngrx

I will mention ngrx as this is the only state library, in my own opinion, that actually have a deep integration with Angular. This is really easy to use, after you understand the flux pattern. I even learn this by doing a React+Redux course in EggHead. So, yeah. The how to use is Redux.

New Features

Some of the other interesting features in Angular 2 are: Form Builder Change Detection Templating Routing Annotations Observables Shadow DOM

Differences Between Angular 1 & 2

Old School Angular 1.xAngular 1.x Best PracticesTransitional ArchitectureAngular 2
Nested scopes ("$scope", watches)Used heavilyAvoidedAvoidedGone
Directives vs controllersUse as alternativesUsed togetherDirectives as componentsComponent directives
Controller and service implementationFunctionsFunctionsES6 classesES6 classes
Module systemAngular's modulesAngular's modulesES6 modulesES6 modules
Transpiler requiredNoNoTypeScriptTypeScript

ES6

JavaScript was created in 1995, but the language is still thriving today. There are subsets, supersets, current versions and the latest version ES6 that brings a lot of new features. Some of the highlights: Classes Arrow Functions Template Strings Inheritance Constants and Block Scoped Variables Spread and Rest operators Destructuring Modules

Classes

Classes are a new feature in ES6, used to describe the blueprint of an object and make EcmaScript's prototypical inheritance model function more like a traditional class-based language.

1
2
3
4
5
6
7
8
class Hamburger {
  constructor() {
    // This is the constructor.
  }
  listToppings() {
    // This is a method.
  }
}

Traditional class-based languages often reserve the word this to reference the current (runtime) instance of the class. In Javascript this refers to the calling context and therefore can change to be something other than the object.

Object

An object is an instance of a class which is created using the new operator. When using a dot notation to access a method on the object, this will refer to the object to the left of the dot.

1
2
let burger = new Hamburger();
burger.listToppings();

In the snippet above, whenever this is used from inside class Hamburger, it will refer to object burger.

Changing Caller Context

JavaScript code can optionally supply this to a method at call time using one of the following.

1
2
3
Function.prototype.call(object [,arg, ...])
Function.prototype.bind(object [,arg, ...])
Function.prototype.apply(object [,argsArray])

A Refresher on this

Inside a JavaScript class we'll be using this keyword to refer to the instance of the class. E.g., consider this case:

1
2
3
4
5
6
7
8
9
class Toppings {
  ...

  formatToppings() { /* implementation details */ }

  list() {
    return this.formatToppings(this.toppings);
  }
}

Here this refers to an instance of the Toppings class. As long as the list method is called using dot notation, like myToppings.list(), then this.formatToppings(this.toppings) invokes the formatToppings() method defined on the instance of the class. This will also ensure that inside formatToppings, this refers to the same instance.

However, this can also refer to other things. There are two basic cases that you should remember.

1)Method invocation:

1
someObject.someMethod();

Here, this used inside someMethod will refer to someObject, which is usually what you want.

2)Function invocation:

1
 someFunction();

Here, this used inside someFunction can refer to different things depending on whether we are in "strict" mode or not. Without using the "strict" mode, this refers to the context in which someFunction() was called. This is rarely what you want, and it can be confusing when this is not what you were expecting, because of where the function was called from. In "strict" mode, this would be undefined, which is slightly less confusing.

EX:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
(function() {

  'use strict';

  var myObject = {
    foo: 'bar',
    someMethod: function() {
      console.log(this);
    }
  };

  function someMethod() {
    console.log(this);
  }

  myObject.someMethod();
  someMethod();

})();

console log

1
2
3
4
5
6
7
[object Object] {
  foo: "bar",
  someMethod: function someMethod() {
      window.runnerWindow.proxyConsole.log(this);
    }
}
undefined

One of the implications is that you cannot easily detach a method from its object. Consider this example:

1
2
var log = console.log;
  log('Hello');

In many browsers this will give you an error. That's because log expects this to refer to console, but the reference was lost when the function was detached from console.

This can be fixed by setting this explicitly. One way to do this is by using bind() method, which allows you to specify the value to use for this inside the bound function.

1
2
 var log = console.log.bind(console);
  log('Hello');

You can also achieve the same using Function.call and Function.apply, but we won't discuss this here.

Another instance where this can be confusing is with respect to anonymous functions, or functions declared within other functions. Consider the following:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class ServerRequest {
   notify() {
     ...
   }
   fetch() {
     getFromServer(function callback(err, data) {
        this.notify(); // this is not going to work
     });
   }
}

In the above case this will not point to the expected object: in "strict" mode it will be undefined. This leads to another ES6 feature - arrow functions, which will be covered next.

Arrow Functions

ES6 offers some new syntax for dealing with this: "arrow functions". Arrow functions also make higher order functions much easier to work with.

The new "fat arrow" notation can be used to define anonymous functions in a simpler way. Consider the following example:

1
2
3
4
items.forEach(function(x) {
    console.log(x);
    incrementedItems.push(x+1);
  });

This can be rewritten as an "arrow function" using the following syntax:

1
2
3
4
items.forEach((x) => {
    console.log(x);
    incrementedItems.push(x+1);
  });

Functions that calculate a single expression and return its values can be defined even simpler:

1
incrementedItems = items.map((x) => x+1);

The latter is almost equivalent to the following:

1
2
3
incrementedItems = items.map(function (x) {
    return x+1;
  });

There is one important difference, however: arrow functions do not set a local copy of this, arguments, super, or new.target. When this is used inside an arrow function JavaScript uses the this from the outer scope. Consider the following example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Toppings {
  constructor(toppings) {
    this.toppings = Array.isArray(toppings) ? toppings : [];
  }
  outputList() {
    this.toppings.forEach(function(topping, i) {
      console.log(topping, i + '/' + this.toppings.length);  // `this` will be undefined
    });
  }
}

var myToppings = new Toppings(['cheese', 'lettuce']);

myToppings.outputList();

Let's try this code on http://jsbin.com. As we see, this gives us an error, since this is undefined inside the anonymous function.

Now, let's change the method to use the arrow function:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Toppings {
  constructor(toppings) {
    this.toppings = Array.isArray(toppings) ? toppings : [];
  }
  outputList() {
    this.toppings.forEach((topping, i) => {
      console.log(topping, i + '/' + this.toppings.length)  // `this` works!
    });
  }
}

var myToppings = new Toppings(['cheese', 'lettuce']);

myToppings.outputList();

Let's try this code on http://jsbin.com. Here this inside the arrow function refers to the instance variable. Warning arrow functions do not have their own arguments variable, which can be confusing to veteran JavaScript programmers. super and new.target are also scoped from the outer enclosure.

Template Strings

In traditional JavaScript, text that is enclosed within matching " or ' marks is considered a string. Text within double or single quotes can only be on one line. There was no way to insert data into these strings. This resulted in a lot of ugly concatenation code that looked like:

1
2
3
4
var name = 'Sam';
var age = 42;

console.log('hello my name is ' + name + ' I am ' + age + ' years old');

ES6 introduces a new type of string literal that is marked with back ticks (`). These string literals can include newlines, and there is a string interpolation for inserting variables into strings:

1
2
3
4
var name = 'Sam';
var age = 42;

console.log(`hello my name is ${name}, and I am ${age} years old`);

There are all sorts of places where this kind of string can come in handy, and front-end web development is one of them.

Observables

Before you get into the meat of Angular 2 Observables, it is important to first understand the problem you are trying to solve.

A frequently encountered scenario in software is where you are expecting some entity to broadcast that something happened; let's call this an "event" (distinct from a browser event). You would like to hook into this entity and attach behavior to it whenever an event occurs. You would also like to be able to detach from this entity when you no longer care about the events it is broadcasting.

There is more nuance and additional complexity to Observables that this chapter will cover, but this concept of events underscores the fundamental pattern that is useful to you as the developer.

The Observer Pattern

The Observer Pattern isn't a library or framework. It is just a software design pattern upon which ReactiveX Observables are built. Many languages and libraries implement this pattern, and ReactiveX is just one of these implementations; however, ReactiveX is the one that Angular 2 has formally incorporated into itself.

The Observer Pattern describes the relationship between subject, which was described as the "entity" earlier, and its observers. The subject is aware of any observers that are watching it. When an event is emitted, the subject is able to pass this event to each observer via methods that are provided when the observer begins to subscribe it.

ReactiveX and RxJS

The ReactiveX library is implemented in numerous languages, including Python, Java, and Ruby. RxJS, the JavaScript implementation of the ReactiveX library, is the dependency that Angular 2 utilizes to incorporate Observables into native framework behavior. Similar to Promises, you can create a standalone Observable instance through direct instantiation, but many Angular 2 methods and services will also utilize an Observable interface by default.

Observables in Angular 2

Angular 2 integrates Observables in a wide variety of ways. If you are new to them, you may initially feel odd using them. However, it is important you recognize that Observables provide a superior software development pattern.

Along with the bulk RxJS module rxjs/Rx, you are also provided with the stripped down Observable module rxjs/Observable. This minimal module allows individual pieces of non-essential behavior to be imported as required in order to reduce module bloat. For example, when using this lightweight Observable module, using operators or other such ReactiveX conventions necessitates that you explicitly incorporate these modules, in order to extend the available Observable interface.

Observables and Promises

Both Observables and Promises offer solutions to asynchronous constructs, but Observables are more robust, extensible, and useful. Although Promises are available by default in the ES6 specification, you will quickly realize that they become brittle when you attempt to apply them outside the realm of basic application behavior.

The ReactiveX library offers powerful tooling to which Promises cannot compare. Observables are composable, allowing you to transform and combine them into new Observables. They also encapsulate the concept of a continuous stream of events-a paradigm that is encountered in client-side programming extremely frequently and that Promises do not translate well to

Basic utilization of Observables with HTTP

In Angular 2, the Http module now by default utilizes the Observable pattern to wrap XMLHttpRequest. For developers that are familiar with the pattern, it readily translates to the asynchronous nature of requests to remote resources. For developers that are newer to the pattern, learning the ins and outs of Http Observables is a good way to wrap your head around this new paradigm.

Getting ready

For the purpose of this example, you'll just serve a static JSON file to the application. However note that this would be no different if you were sending requests to a dynamic API endpoint.

Begin by creating a skeleton component, including all the necessary modules for making HTTP requests:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
[app/article.component.ts] 

import {Component} from '@angular/core'; 
import {Http} from '@angular/http'; 

@Component({ 
  selector: 'article', 
  template: `                    
    <h1>{{title}}</h1> 
    <p>{{author}}</p> 
  ` 
}) 
export class ArticleComponent { 
  title:string; 
  body:string; 
  constructor (private http: Http) { 
  } 
} 

For this example, assume there is a JSON file inside the static directory named article.json:

1
2
3
4
5
6
[article.json] 

{ 
  "title": "Orthopedic Doctors Ask City for More Sidewalk Cracks", 
  "author": "Jake Hsu" 
} 

How to do it...

Since you have already injected the Http service, you can begin by defining the get request:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
[app/article.component.ts] 

import {Component} from '@angular/core'; 
import {Http} from '@angular/http'; 

@Component({ 
  selector: 'article', 
  template: `                    
    <h1>{{title}}</h1> 
    <p>{{author}}</p> 
  ` 
}) 
export class ArticleComponent { 
  title:string; 
  body:string; 
  constructor (private http_: Http) { 
    http_.get('static/article.json'); 
  } 
} 

This creates an Observable instance, but you still need to add instructions on how to handle the raw string of the response.

Since you know the request will return JSON, you can utilize the json() method that a Response would expose. This can be done inside the map() method. However, the Observable does not expose the map() method by default, so you must import it from the rxjs module:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
[app/article.component.ts] 

import {Component} from '@angular/core'; 
import {Http} from '@angular/http'; 
import 'rxjs/add/operator/map'; 

@Component({ 
  selector: 'article', 
  template: `                    
    <h1>{{title}}</h1> 
    <p>{{author}}</p> 
  ` 
}) 
export class ArticleComponent { 
  title:string; 
  author:string; 
  constructor (private http_: Http) { 
    http_.get('static/article.json')
.map(response => response.json()); 
  } 
} 

So far so good, but you're still not done. The preceding code will create the Observable instance, but you still have to subscribe to it in order to handle any data it would emit. This can be accomplished with the subscribe() method, which allows you to attach the callback and error handling methods of observer:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
[app/article.component.ts] 

import {Component} from '@angular/core'; 
import {Http} from '@angular/http'; 
import 'rxjs/add/operator/map'; 

@Component({ 
  selector: 'article', 
  template: `                    
    <h1>{{title}}</h1> 
    <p>{{author}}</p> 
  ` 
}) 
export class ArticleComponent { 
  title:string; 
  author:string; 
  constructor (private http_: Http) { 
    http_.get('static/article.json') 
      .map(response => response.json()) 
      .subscribe( 
        article => { 
          this.title = article.title; 
          this.author = article.author; 
        }, 
        error => console.error(error)); 
  } 
} 

With all of this, the GET request will return the JSON file, and the response data will be parsed and its data interpolated into the DOM by the component.

How it works...

The previous section gave a good high-level overview of what was happening, but it is useful to break things down more carefully to understand what each individual step accomplishes.

Observable

The Http service class exposes the methods get(), post(), put(), and so on—all the HTTP verbs that you would expect. Each of these will return Observable, which will emit a Response instance when the request is returned:

1
2
console.log(http_.get('static/article.json')); 
// Observable { ... } 
1
2
Note
It sounds obvious, but Observables are observed by an observer. The observer will wait for Observable to emit objects, which in this example takes the form of Response.

The RxJS map() operator

The Response instance exposes a json() method, which converts the returned serialized payload string into its corresponding in-memory object representation. You would like to be able to pass a regular object to the observer handler, so the ideal tool here is a wedge method that still gives you an Observable in the end:

1
2
3
console.log(http_.get('static/article.json') 
  .map(response => response.json())); 
// Observable {source: Observable, operator: MapOperator, ...} 

Recall that the canonical form of Observables is a stream of events. In this case, we know there will only ever be one event, which is the HTTP response. Nonetheless, all the normal operators that would be used on a stream of events can just as easily be used on this single-event Observable.

In the same way that Array.map() can be used to transform each instance in the array, Observable.map() allows you to transform each event emitted from Observable. More specifically, it creates another Observable that emits the modified event passed from the initial observable.

Subscribe

Observable instances expose a subscribe() method that accepts an onNext handler, an onError handler, and an onCompleted handler as arguments. These handlers correspond to the events in the life cycle of the Observable when it emits Response instances. The parameter for the onNext method is whatever is emitted from the Observable. In this case, the emitted data is the returned value from map(), so it will be the parsed object that has returned after invoking json() on the Response instance.

All these methods are optional, but in this example, the onNext and onError methods are useful.

1
2
Note
Together, these methods when provided to subscribe() constitute what is identified as the observer.
1
2
3
4
5
6
7
8
http_.get('static/article.json') 
  .map(respose => respose.json()) 
  .subscribe( 
    article => { 
      this.title = article.title; 
      this.body = article.body; 
    }, 
    error => console.error(error)); 

With all of this together, the browser will fetch the JSON and parse it, and the subscriber will pass its data to the respective component members.

There's more...

When constructing this recipe piece by piece, if you are watching your browser's network requests as you assemble it, you will notice that the actual GET request is not fired until the subscribe() method is invoked. This is because the type Observable you are using is "cold".

Hot and cold Observables

The "cold" designation means that the Observable does not begin to emit until an observer begins to subscribe to it. This is different from a "hot" Observable, which will emit items even if there are no observers subscribed to it. Since this means that events that occur before an observer is attached are lost, HTTP Observables demand a cold designation.

The onNext method is termed "emission" since there is associated data that is being emitted. The onCompleted and onError methods are termed "notifications," as they represent something of significance, but they do not have an associated event that would be considered part of the stream.

Implementing a Publish-Subscribe model using Subjects

Angular 2 will often provide you with an Observable interface to attach to for free, but it is important to know how they are created, configured, and used. More specifically, it is valuable for you to know how to take Observables and apply them to real scenarios that will be encountered in the client

Getting ready

Suppose you started with the following skeleton application:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
[app/click-observer.component.ts] 

import {Component} from '@angular/core'; 

@Component({ 
  selector: 'click-observer', 
  template: ` 
   <button> 
     Emit event! 
   </button> 
   <p *ngFor="let click of clicks; let i = index"> 
     {{i}}: {{click}} 
   </p> 
  ` 
}) 
export class ClickObserverComponent { 
  clicks:Array<Event> = []; 
} 

Your goal is to convert this so that all the button click events are logged in to the repeated field.

How to do it...

Accomplishing this with a component member method and using it in the click event binding in the template is possible, but this doesn't capture the real value of Observables. You want to be able to expose an Observable on ClickObserverComponent. This will allow any other part of your application to subscribe to these click events and handle them in its own way.

Instead, you would like to be able to funnel the click events from the button into the Observable. With a regular Observable instance, this isn't possible since it is only acting as the Subscribe part of the Publish-Subscribe model. To accomplish the Publish aspect, you must use a Subject instance:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
[app/click-observer.component.ts] 

import {Component} from '@angular/core'; 
import {Subject} from 'rxjs/Subject'; 

@Component({ 
  selector: 'click-observer', 
  template: ` 
   <button> 
     Emit event! 
   </button> 
   <p *ngFor="let click of clicks; let i = index"> 
     {{i}}: {{click}} 
   </p> 
  ` 
}) 
export class ClickObserverComponent { 
  clickEmitter:Subject<Event> = new Subject(); 
  clicks:Array<Event> = []; 
} 

ReactiveX Subjects act as both the Observable and the Observer. Therefore, it exposes both the subscribe() method, used for the Subscribe behavior, and the next() method, used for the Publish behavior

1
2
Note
In this example, the next() method is useful because you want to explicitly specify when an emission should occur and what that emission should contain. There are lots of ways of instantiating Observables in order to implicitly generate emissions, such as (but certainly not limited to) Observable.range(). In these cases, Observable understands how its input behaves, and thus it does not need direction as to when emissions occur and what they should contain.

In this case, you can pass the event directly to next() in the template click handler definition. With this, all that is left is to populate the array by directing the emissions into it:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
[app/click-observer.component.ts] 

import {Component} from '@angular/core'; 
import {Subject} from 'rxjs/Subject'; 

@Component({ 
  selector: 'click-observer', 
  template: ` 
   <button (click)="clickEmitter.next($event)"> 
     Emit event! 
   </button> 
   <p *ngFor="let click of clicks; let i = index"> 
     {{i}}: {{click}} 
   </p> 
  ` 
}) 
export class ClickObserverComponent { 
  clickEmitter:Subject<Event> = new Subject(); 
  clicks:Array<Event> = []; 

  constructor() { 
   this.clickEmitter 
     .subscribe(clickEvent => this.clicks.push(clickEvent)); 
  } 
} 

That's all! With this, you should see click events populate in the browser with each successive button click.

How it works...

ReactiveX Observables and Observers are distinct, but their behavior is mutually compatible in such a way that their union, Subject, can act as either one of them. In this example, the Subject is used as the interface to feed in Event objects as the Publish modality as well as to handle the result that would come out as the Subscribe modality.

There's more...

The way this is constructed might feel a bit strange to you. The component is exposing the Subject instance as the point where your application will attach observer handlers.

However, you want to prevent other parts of the application from adding additional events, which is still possible should they choose to use the next() method. What's more, the Subject instance is referenced directly inside the template and exposing it there may feel a bit odd. Therefore, it is desirable, and certainly good software practice, to only expose the Observable component of the Subject.

To do this, you must import the Observable module and utilize the Subject instance's member method, namely asObservable(). This method will create a new Observable instance that will effectively pipe the observed emissions from the Subject into the new Observable, which will be exposed as a public component member:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
[app/article.component.ts] 

import {Component} from '@angular/core'; 
import {Observable} from 'rxjs/Observable'; 
import {Subject} from 'rxjs/Subject'; 

@Component({ 
  selector: 'click-observer', 
  template: ` 
   <button (click)="publish($event)"> 
     Emit event! 
   </button> 
   <p *ngFor="let click of clicks; let i = index"> 
     {{i}}: {{click}} 
   </p> 
  ` 
}) 
export class ClickObserverComponent { 
  clickEmitter: Observable<Event>;
private clickSubject_: Subject<Event> = new Subject(); 
  clicks:Array<Event> = []; 

  constructor() { 
   this.clickEmitter = this.clickSubject_.asObservable(); 
   this.clickEmitter.subscribe(clickEvent =>  
     this.clicks.push(clickEvent)); 
  } 

  publish(e:Event):void { 
   this.clickSubject_.next(e); 
  } 
} 

Now even though only this component is referencing clickEmitter, every component that uses clickEmitter will not need or be able to touch the source, Subject.

Native RxJS implementation

This has all been a great example, but this is such a common pattern in that the RxJS library already provides a built-in way of implementing it. The Observable class exposes a static method fromEvent(), which takes in an element that is expected to generate events and the event type to listen to.

However, you need a reference to the actual element, which you currently do not have. For the present implementation, the Angular 2 ViewChild faculties will give you a very nice reference to the button, which will then be passed to the fromEvent() method once the template has been rendered:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
[app/click-observer.component.ts] 

import {Component, ViewChild, ngAfterViewInit}  
  from '@angular/core'; 
import {Observable} from 'rxjs/Observable'; 
import 'rxjs/add/observable/fromEvent'; 

@Component({ 
  selector: 'click-observer', 
  template: ` 
   <button #btn> 
     Emit event! 
   </button> 
   <p *ngFor="let click of clicks; let i = index"> 
     {{i}}: {{click}} 
   </p> 
  ` 
}) 
export class ClickObserverComponent implements AfterViewInit { 
  @ViewChild('btn') btn; 
  clickEmitter:Observable<Event>; 
  clicks:Array<Event> = []; 

  ngAfterViewInit() { 
    this.clickEmitter = Observable.fromEvent( 
        this.btn.nativeElement, 'click'); 
   this.clickEmitter.subscribe(clickEvent =>  
        this.clicks.push(clickEvent)); 
  } 
} 

With all of this, the component should still behave identically

Creating an Observable authentication service using BehaviorSubjects

One of the most obvious and useful cases of the Observer Pattern is the one in which a single entity in your application unidirectionally communicates information to a field of listeners on the outside. These listeners would like to be able to attach and detach freely from the single broadcasting entity. A good initial example of this is the login/logout component.

Getting ready

Suppose you have the following skeleton application:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
[app/login.component.ts] 

import {Component} from '@angular/core'; 

@Component({ 
  selector: 'login', 
  template: ` 
    <button *ngIf="!loggedIn"  
            (click)="loggedIn=true"> 
      Login 
    </button> 
    <button *ngIf="loggedIn"  
            (click)="loggedIn=false"> 
      Logout 
    </button> 
  ` 
}) 
export class LoginComponent { 
  loggedIn:boolean = false; 
} 

As it presently exists, this component will allow you to toggle between the login/logout button, but there is no concept of shared application state, and other components cannot utilize the login state that this component would track.

You would like to introduce this state to a shared service that is operated using the Observer Pattern.

How to do it...

Begin by creating an empty service and injecting it into this component:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
[app/authentication.service.ts] 

import {Injectable} from '@angular/core'; 

@Injectable() 
export class AuthService { 
  private authState_: AuthState; 
} 

export const enum AuthState { 
   LoggedIn, 
   LoggedOut 
} 

Notice that you are using a TypeScript const enum to keep track of the user's authentication state.

1
2
3
4
5
6
Note
If you're new to ES6 and TypeScript, these keywords may feel a bit bizarre to you. The const keyword is from the ES6 specification, signifying that this value is read only once declared. In vanilla ES6, this will throw an error, usually SyntaxError, at runtime. With TypeScript compilation though, const will be caught at compile time.

The enum keyword is an offering of TypeScript. It is not dissimilar to a regular object literal, but note that the enum members do not have values.

Throughout the application, you will reference these via AuthState.LoggedIn and AuthState.LoggedOut. If you reference the compiled JavaScript that TypeScript generates, you will see that these are actually assigned integer values. But for the purposes of building large applications, this allows us to develop a centralized repository of possible AuthState values without worrying about their actual values.

Injecting the authentication service

As the skeleton service currently exists, you are going to instantiate a Subject that will emit AuthState, but there is no way available currently to interact with it. You will set this up in a bit. First, you must inject this service into your component:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
[app/app.module.ts] 

import {NgModule} from '@angular/core'; 
import {BrowserModule} from '@angular/platform-browser'; 
import {LoginComponent} from './login.component'; 
import {AuthService} from './authentication.service'; 

@NgModule({ 
  imports: [ 
    BrowserModule 
  ], 
  declarations: [ 
    LoginComponent 
  ], 
  providers: [ 
    AuthService   
  ], 
  bootstrap: [ 
    LoginComponent 
  ] 
}) 
export class AppModule {} 

This is all well and good, but the service is still unusable as is.

1
2
Tip
Note that the path you import your AuthService from may vary depending on where it lies in your file tree.

Adding BehaviorSubject to the authentication service

The core of this service is to maintain a global application state. It should expose itself to the rest of the application by letting other parts say to the service, "Let me know whenever the state changes. Also, I'd like to know what the state is right now." The perfect tool for this task is BehaviorSubject.

1
2
Note
RxJS Subjects also have several subclasses, and BehaviorSubject is one of them. Fundamentally, it follows all the rhythms of Subjects, but the main difference is that it will emit its current state to any observer that begins to listen to it, as if that event is entirely new. In cases like this, where you want to keep track of the state, this is extremely useful.

Add a private BehaviorSubject (initialized to the LoggedOut state) and a public Observable to AuthService:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
[app/authentication.service.ts] 

import {Injectable} from '@angular/core'; 
import {BehaviorSubject} from 'rxjs/BehaviorSubject'; 
import {Observable} from 'rxjs/Observable'; 

@Injectable() 
export class AuthService { 
  private authManager_:BehaviorSubject<AuthState> 
    = new BehaviorSubject(AuthState.LoggedOut); 
  private authState_:AuthState; 
  authChange:Observable<AuthState>;
constructor() { 
    this.authChange = this.authManager_.asObservable(); 
  } 
} 

export const enum AuthState { 
   LoggedIn, 
   LoggedOut 
} 

Adding API methods to the authentication service

Recall that you do not want to expose the BehaviorSubject instance to outside actors. Instead, you would like to offer only its Observable component, which you can openly subscribe to. Furthermore, you would like to allow outside actors to set the authentication state, but only indirectly. This can be accomplished with the following methods:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
[app/authentication.service.ts] 

import {Injectable} from '@angular/core'; 
import {BehaviorSubject} from 'rxjs/BehaviorSubject'; 
import {Observable} from 'rxjs/Observable'; 

@Injectable() 
export class AuthService { 
  private authManager_:BehaviorSubject<AuthState> 
    = new BehaviorSubject(AuthState.LoggedOut); 
  private authState_:AuthState; 
  authChange:Observable<AuthState>; 

  constructor() { 
    this.authChange = this.authManager_.asObservable(); 
  } 
  login():void { 
    this.setAuthState_(AuthState.LoggedIn); 
  } 
  logout():void { 
    this.setAuthState_(AuthState.LoggedOut); 
  } 
  emitAuthState():void { 
    this.authManager_.next(this.authState_); 
  } 
  private setAuthState_(newAuthState:AuthState):void { 
    this.authState_ = newAuthState; 
    this.emitAuthState(); 
  } 
} 

export const enum AuthState { 
   LoggedIn, 
   LoggedOut 
} 

Outstanding! With all of this, outside actors will be able to subscribe to authChange Observable and will indirectly control the state via login() and logout().

1
2
Tip
Note that the Observable component of BehaviorSubject is named authChange. Naming the different components of the elements in the Observer Pattern can be tricky. This naming convention was selected to represent what an event emitted from the Observable actually meant. Quite literally, authChange is the answer to the question, "What event am I observing?". Therefore, it makes good semantic sense that your component subscribes to authChanges when the authentication state changes.

Wiring the service methods into the component

LoginComponent does not yet utilize the service, so add in its newly created methods:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
[app/login.component.ts] 

import {Component} from '@angular/core'; 
import {AuthService, AuthState} from './authentication.service'; 

@Component({ 
  selector: 'login', 
  template: ` 
    <button *ngIf="!loggedIn"  
            (click)="login()"> 
      Login 
    </button> 
    <button *ngIf="loggedIn"  
            (click)="logout()"> 
      Logout 
     </button> 
  ` 
}) 
export class LoginComponent { 
  loggedIn:boolean; 

  constructor(private authService_:AuthService) { 
    authService_.authChange.subscribe( 
      newAuthState => 
        this.loggedIn = (newAuthState === AuthState.LoggedIn)); 
  } 

  login():void { 
    this.authService_.login(); 
  } 

  logout():void { 
    this.authService_.logout(); 
  } 
} 

With all of this in place, you should be able to see your login/logout buttons function well. This means you have correctly incorporated Observable into your component.

1
2
Tip
This recipe is a good example of conventions you're required to maintain when using public/private. Note that the injected service is declared as a private member and wrapped with public component member methods. Anything that another part of the application calls or anything that is used inside the template should be a public member.

How it works...

Central to this implementation is that each component that is listening to Observable has an idempotent handling of events that are emitted. Each time a new component is connected to Observable, it instructs the service to emit whatever the current state is, using emitAuthState(). Necessarily, all components don't behave any differently if they see the same state emitted multiple times in a row; they will only alter their behavior if they see a change in the state.

Notice how you have totally encapsulated the authentication state inside the authentication service, and at the same time, have exposed and utilized a reactive API for the entire application to build upon.

There's more...

Two critical components of hooking into services such as these are the setup and teardown processes. A fastidious developer will have noticed that even if an instance of LoginComponent is destroyed, the subscription to Observable will still persist. This, of course, is extremely undesirable!

Fortunately, the subscribe() method of Observables returns an instance of Subscription, which exposes an unsubscribe() method. You can therefore capture this instance upon the invocation of subscribe() and then invoke it when the component is being torn down.

Similar to listener teardown in Angular 1, you must invoke the unsubscribe method when the component instance is being destroyed. Happily, the Angular 2 life cycle provides you with such a method, ngOnDestroy, in which you can invoke unsubscribe():

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
[app/login.component.ts] 

import {Component, ngOnDestroy} from '@angular/core'; 
import {AuthService, AuthState} from './authentication.service'; 
import {Subscription} from 'rxjs/Subscription'; 

@Component({ 
  selector: 'login', 
  template: ` 
    <button *ngIf="!loggedIn"  
            (click)="login()"> 
      Login 
    </button> 
    <button *ngIf="loggedIn"  
            (click)="logout()"> 
      Logout 
    </button> 
  ` 
}) 
export class LoginComponent implements OnDestroy { 
  loggedIn:boolean; 
  private authChangeSubscription_: Subscription; 

  constructor(private authService_:AuthService) { 
    this.authChangeSubscription_ =  
      authService_.authChange.subscribe( 
        newAuthState => 
          this.loggedIn = (newAuthState === AuthState.LoggedIn)); 
  } 

  login():void { 
    this.authService_.login(); 
  } 
  logout():void { 
    this.authService_.logout(); 
  } 
  ngOnDestroy() { 
    this.authChangeSubscription_.unsubscribe(); 
  } 
} 

Now your application is safe from memory leaks should any instance of this component ever be destroyed in the lifetime of your application.

Building a generalized Publish-Subscribe service to replace $broadcast, $emit, and $on

In Angular 1, the $emit and $broadcast behaviors were indeed very useful tools. They gave you the ability to send custom events upwards and downwards through the scope tree to any listeners that might be waiting for such an event. This pushed the developer towards a very useful pattern: the ability for many components to be able to transmit events to and from a central source. However, using $emit and $broadcast for such a purpose was grossly inappropriate; they had the effect of feeding the event through huge numbers of scopes only to reach the single intended target.

1
2
3
4
Note
In the previous edition of this book, the corresponding recipe demonstrated how to build a Publish-Subscribe service that used the $emit and $rootScope injection. The version in this recipe, although different in a handful of ways, achieves similar results in a substantially cleaner and more elegant fashion.

It is preferable to create a single entity that can serve as a generic throughway for events to pass from publishers to their subscribers.

Using QueryLists and Observables to follow changes in ViewChildren

One very useful piece of behavior in components is the ability to track changes to the collections of children in the view. In many ways, this is quite a nebulous subject, as the number of ways in which view collections can be altered is numerous and subtle. Thankfully, Angular 2 provides a solid foundation for tracking these changes.

Getting ready

Suppose you begin with the following skeleton application:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
[app/inner.component.ts] 

import {Component, Input} from '@angular/core'; 

@Component({ 
  selector: 'inner', 
  template: `<p>{{val}}` 
}) 
export class InnerComponent { 
  @Input() val:number; 
} 
[app/outer.component.ts] 

import {Component} from '@angular/core'; 

@Component({ 
  selector: 'outer', 
  template: ` 
    <button (click)="add()">Moar</button> 
    <button (click)="remove()">Less</button> 
    <button (click)="shuffle()">Shuffle</button> 
    <inner *ngFor="let i of list" 
            val="{{i}}"> 
    </inner> 
  `...
  ```



###<b>Angular Installation Steps</b>

##Step 1. Set up the Development Environment

You need to set up your development environment before you can do anything.

Install Node.js and npm if they are not already on your machine.

# Install Nodejs
1
2
sudo apt-get update
sudo apt-get install nodejs
1
If the package in the repositories suits your needs, this is all that you need to do to get set up with Node.js. In most cases, you'll also want to also install npm, which is the Node.js package manager. You can do this by typing:

sudo apt-get install npm

1
2
3
4
This will allow you to easily install modules and packages to use with Node.js.


Then install the Angular CLI globally.

npm install -g @angular/cli

1
2
3
4
5
6
7
Now Installation of Node,Npm and angular are completed. Now we need to create angular project

#Step 2. Create a new project 

Open a terminal window.

Generate a new project and default app by running the following command:

ng new my-app

1
2
3
4
5
Now new project will be created with my-app.

to run project

#Step 3. Serve the application

ng serve --open ``` here --open is for after completing execution it will open in default browser.

The ng serve command launches the server, watches your files, and rebuilds the app as you make changes to those files.

Using the --open (or just -o) option will automatically open your browser on http://localhost:4200/.

Now your application run with default welcome page