Category Archives: Javascript

Angular 2 Nested Routing – Demo

Angular 2 routing supports nested routing which was kind of lacking in Angular 1.*, unless you use UI-Router in Angular 1. Nested routing can be achieved in Angular using the Component router, which is pretty powerful and configurable and most of all supports deep nested routing, using the component router, you can declaratively specify application states, manage state transitions while taking care of the URL, and load bundles on demand. This blog post will cover how to set up the nested routing, it includes nesting up to 3 levels, but you can do much deeper nesting as well.

So this demo looks some thing like this

nested-routing-1

nested-routing-2

Essentially we have an app (which is a a component) which has following 2 components (child components)

  • Customers – This component has further child components
    • Customers List
    • Prospect Customers
    • Inquiries
  • Orders – This component has further child components
    • Completed Orders
    • In Progress Orders

Lets looks at first app component and lets set up the Main navigation, here is how the app component html looks like, left is navigation area and right is the router outlet where either orders or customer component will be displayed depending upon the route selection.

router-outlet:  It acts as a placeholder that Angular dynamically fills based on the current router state.

nested-routing-3

In the app module we need to define  the routes, here is how the app module looks like

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { RouterModule, Route } from '@angular/router';
import { CustomersModule } from './customers/customers.module';
import { OrdersModule } from './orders/orders.module';
import { CustomersComponent } from './customers/customers.component';
import { OrdersComponent } from './orders/orders.component';
import { AppComponent } from './app.component';
const appRoutes = [
  {
    path: 'customers',
    component: CustomersComponent,
    loadChildren: './customers/customers.module#CustomersModule',
    data: { preload: true }
  },
  {
    path: 'orders',
    component: OrdersComponent,
    loadChildren: './orders/orders.module#OrdersModule',
    data: { preload: true }

  },
  {
    path: '',
    redirectTo: '/customers',
    pathMatch: 'full',
  },
]
@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule, FormsModule, HttpModule, CustomersModule, OrdersModule,
    RouterModule.forRoot(appRoutes)
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

 

As you can see we have defined the routes to load Orders and Customers component as well as redirect to customers component by default in case of empty route path.

Also please note the RouterModule.forRoot(appRoutes),  this configures the routing for root module.

RouterModule can be imported multiple times: once per lazily-loaded bundle. Since the router deals with a global shared resource–location, we cannot have more than one router service active. That is why there are two ways to create the module:

  • RouterModule.forRoot
    • forRoot creates a module that contains all the directives, the given routes, and the router service itself.
  • RouterModule.forChild.
    • forChild creates a module that contains all the directives and the given routes, but does not include the router service.

When registered at the root, the module should be used as RouterModule.forRoot as shown in the app module above. For submodules and lazy loaded submodules the module should be used as RouterModule.forChild as shown below for CustomersModule or OrderModules.

loadChildren is a reference to lazy loaded child routes. In the above case if loadChildren is not specified then when user hits http://localhost:4200 then it routes to http://localhost:4200/customers, and displays the customers component but does not load the child components. When we specify loadChildren then it loads the child component.

For loadChildren Angular will fetch the module at the location and then load the routes defined in its router config. The path to the file and name of the module is separated by #. The Router reads the ModuleName given after # and loads the module accordingly. So we did not load CustomersModule and OrdersModule in our AppComponent, instead used loadChildren property in the routing config to lazy load our modules.

By default it loads customer component in the main area, so lets look at the customer component, here is how the html for customer component looks like

nested-routing-4.JPG

Customers List, Prospect Customers and Inquiries are the bootstrap tabs, clicking on those loads respective component in the router-outlet area.

Here is how the customer module looks like

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterModule, Route } from '@angular/router';
import { CustomersComponent } from './customers.component';
import { CustomersListComponent } from './customers-list/customers-list.component';
import { ProspectsComponent } from './prospects/prospects.component';
import { InquiriesComponent } from './inquiries/inquiries.component';
import { CustomersService } from "./customers.service";
const customersRoutes = [
  {
    path: 'customers',
    component: CustomersComponent,
    children: [
      {
        path: '',
        redirectTo: '/customers/list',
        pathMatch: 'full',
      },
      {
        path: 'list',
        component: CustomersListComponent
      },
      {
        path: 'prospects',
        component: ProspectsComponent
      },
      {
        path: 'inquiries',
        component: InquiriesComponent
      }
    ]
  }
]
@NgModule({
  imports: [
    CommonModule,
    RouterModule.forChild(customersRoutes)
  ],
  declarations: [CustomersComponent, CustomersListComponent, ProspectsComponent, InquiriesComponent],
  providers: [CustomersService]
})
export class CustomersModule { }

 

Over here we are defining routes to load child components of customers component.

Please note RouterModule.forChild(customersRoutes), this configures the child routes for Customer component.

We are also redirecting to Customers list component by default in case of empty routes. So when user hits the URL http://localhost:4200/ app module routing redirects to http://localhost:4200/customers as well as tells to load child components as mentioned above not in the customers component we have a redirect specified that in case of empty route redirect to ‘/customers/list‘ i.e. http://localhost:4200/customer/list.

Screen shot for customers list is covered above,below one shows child components (Prospect and Inquiries respectively).

nested-routing-5nested-routing-6

Similar to customers component Orders Component has its own child component, here is how the html looks like

nested-routing-7

and its module looks some thing like this

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterModule, Route } from '@angular/router';
import { OrdersComponent } from './orders.component';
import { CompletedOrdersComponent } from './completed-orders/completed-orders.component';
import { InProgressOrdersComponent } from './in-progress-orders/in-progress-orders.component';
import { OrdersService } from './orders.service';
const ordersRoutes = [
  {
    path: 'orders',
    component: OrdersComponent,
    children: [
      {
        path: '',
        redirectTo: '/orders/completed',
        pathMatch: 'full',
      },
      {
        path: 'completed',
        component: CompletedOrdersComponent
      },
      {
        path: 'inprogress',
        component: InProgressOrdersComponent
      }
    ]
  }
]
@NgModule({
  imports: [
    CommonModule,
    RouterModule.forChild(ordersRoutes)
  ],
  declarations: [OrdersComponent, CompletedOrdersComponent, InProgressOrdersComponent],
  providers: [OrdersService]
})
export class OrdersModule { }

Screen shot for Completed orders is covered above,below one shows in-progress orders child components.

nested-routing-9

Complete source can be found on GitHub

Angular 2 Pipes – Force Angular 2 to execute Pipe

Earlier in the blogs we had seen samples of Pipes, I am referring to the sample example below again. Below is the grid for displaying list of persons and as you type in the something in multiple filters like name, email and company, that filter criteria will get applied to that persons data and filter the grid items.

blog-oioe-multiple-params-2

blog-oioe-multiple-params-3

Below is the pipes transform implementation

import {Pipe, PipeTransform } from '@angular/core';
@Pipe({
    name: 'personSearch'
})
export class PersonSearchPipe implements PipeTransform {
    transform(items: Array, nameSearch: string, emailSearch: string, companySearch: string){
        if (items && items.length){
            return items.filter(item =>{
                if (nameSearch && item.name.toLowerCase().indexOf(nameSearch.toLowerCase()) === -1){
                    return false;
                }
                if (emailSearch && item.email.toLowerCase().indexOf(emailSearch.toLowerCase()) === -1){
                    return false;
                }
                if (companySearch && item.company.toLowerCase().indexOf(companySearch.toLowerCase()) === -1){
                    return false;
                }
                return true;
           })
        }
        else{
            return items;
        }
    }
}

You need to register the pipes with the module

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';

import { AppComponent } from './app.component';
import { PersonSearchPipe } from './personSearch.pipe';
@NgModule({
  declarations: [
    AppComponent,
    PersonSearchPipe
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule
  ],
  providers: [],
  bootstrap: [AppComponent],

})
export class AppModule { }

blog-oioe-multiple-params-1

In the above grid for displaying list of persons and as you type in the something in multiple filters like name, email and company, that filter criteria will get applied to that persons data and filter the grid items. This works perfectly fine but what if he an item is added to the filter list which matches the filter criteria then this item will not be appended to the filter list, for that to happen we have to replace the array by creating a copy of it and assigning it back to the components persons array which does not seem to be very intuitive way of doing it.

Here is the component code, I have added a setInterval which appends the person item to the array every 5 seconds on the

 ngOnInit() {
    setInterval(() => {
      this.ngzone.run(() => {
        let person = JSON.parse(JSON.stringify(this.persons[0]));
        this.persons.push(person);
        console.log("Length: " + this.persons.length);
      })
    }, 5000)
  }

Now when we have applied filter these appended elements will not be available in the UI as the pipes are not executing , so work around this we can force the pipe to be executed, this can be achieved by adding the fake filter like date time or random number to the pipe and assign the new value every time. In the above scenario I will add the Datetime to the component and pass the same to Pipe, below is the ngOnInit code

 ngOnInit() {
    setInterval(() => {
      this.ngzone.run(() => {
        let person = JSON.parse(JSON.stringify(this.persons[0]));
        this.persons.push(person);
        this.currentDatetime = new Date();
        console.log("Length: " + this.persons.length);
      })
    }, 5000)
  }

Here is the updated pipe code

import {Pipe, PipeTransform } from '@angular/core';
@Pipe({
    name: 'personSearch'
})
export class PersonSearchPipe implements PipeTransform {
    transform(items: Array<any>, nameSearch: string, emailSearch: string, companySearch: string, currentDatetime: Date){
        if (items && items.length){
            return items.filter(item =>{
                if (nameSearch && item.name.toLowerCase().indexOf(nameSearch.toLowerCase()) === -1){
                    return false;
                }
                if (emailSearch && item.email.toLowerCase().indexOf(emailSearch.toLowerCase()) === -1){
                    return false;
                }
                if (companySearch && item.company.toLowerCase().indexOf(companySearch.toLowerCase()) === -1){
                    return false;
                }
                return true;
           })
        }
        else{
            return items;
        }
    }
}

here is the updated Html

blog-force-pipe-to-execute-1

Now your filter will work like charm, as u can see “Johanna Chaney” person getting appended.

blog-force-pipe-to-execute-2

Here is the attached source code 

 

Angular 2 – Pipes passing multiple filters to Pipes

In earlier blog posts we had seen simplistic scenario of using pipes, but what if there is requirement to pass multiple parameters to Pipes in Angular 2,below example demonstrates the same.

Below is the grid for displaying list of persons and as you type in the something in multiple filters like name, email and company, that filter criteria will get applied to that persons data and filter the grid items.

blog-oioe-multiple-params-2

blog-oioe-multiple-params-3

For creating custom pipes you need to create class that implements PipeTransform Interface, this class is then decorated with @Pipe decorator. From the PipeTranform interface you need to implement transform method,  for passing multiple filter parameters to the pipe in the transform method you need to add those parameters like shown below in the code snippet. (nameSearch: string, emailSearch: string, companySearch: string). Transform method implementation then can decide the filtering based on the parameters passed, you can implement your own custom logic over here.

import {Pipe, PipeTransform } from '@angular/core';
@Pipe({
    name: 'personSearch'
})
export class PersonSearchPipe implements PipeTransform {
    transform(items: Array, nameSearch: string, emailSearch: string, companySearch: string){
        if (items && items.length){
            return items.filter(item =>{
                if (nameSearch && item.name.toLowerCase().indexOf(nameSearch.toLowerCase()) === -1){
                    return false;
                }
                if (emailSearch && item.email.toLowerCase().indexOf(emailSearch.toLowerCase()) === -1){
                    return false;
                }
                if (companySearch && item.company.toLowerCase().indexOf(companySearch.toLowerCase()) === -1){
                    return false;
                }
                return true;
           })
        }
        else{
            return items;
        }
    }
}

You need to register the PersonSearchPipe to component module like show below

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';

import { AppComponent } from './app.component';
import { PersonSearchPipe } from './personSearch.pipe';
@NgModule({
  declarations: [
    AppComponent,
    PersonSearchPipe
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule
  ],
  providers: [],
  bootstrap: [AppComponent],

})
export class AppModule { }

 

In the HTML for the component add the filter like shown below

blog-oioe-multiple-params-1

 

 

Angular 2 – Passing data to child components

It is very common requirement to pass the data from Parent component to child component. In angular this can be achieved using using the @Input decorator, to define an input for a component, we use the @Input decorator. This decorator tells Angular to treat passed value as an input binding

Below is the Partner Component which has child component Partner contacts, their HTML looks some thing like this
Partner Component

{{partner.name}} {{partner.website}}
<app-partners-contacts-list [contacts]="partner.contacts"></app-partners-contacts-list>

Inside partner component we have child component partner contact list

<app-partners-contacts-list [contacts]="partner.contacts"></app-partners-contacts-list>

Partner Contact List: As u can see for the child component we are setting the partner.contacts array value to the the contacts @Input property on the child component. Child component looks some thing like this

import { Component, OnInit, Input } from '@angular/core';
import { PartnerContacts } from './../../partner.model';
@Component({
  selector: 'app-partners-contacts-list',
  templateUrl: './partners-contacts-list.component.html'
})
export class PartnersContactsListComponent implements OnInit {
  @Input() contacts: PartnerContacts[];
  constructor() { }

  ngOnInit() {
    console.log(this.contacts);
  }

}

As you can see we have declared an @Input property inside the child component so that we can set the this value from parent component.

HTML : It just a table iterating through contacts array.

Angular 2 Custom Pipes

In Angular 1.x we had used Filters extensively be it inbuilt ones or the custom ones. In Angular 2.x filters have been re-branded/renamed to Pipes. Below is an example for building custom pipes in Angular 2.x.

Below is the grid for displaying list of persons and as you type in the something in search criteria it will apply that filter criteria to person name property and filter the grid items.

personlist

personfilteredlist

For creating custom pipes you need to create class that implements PipeTransform Interface, this class is then decorated with @Pipe decorator. From the PipeTranform interface you need to implement transform method, below is the code snippet for the same.

import {Pipe, PipeTransform } from '@angular/core';
@Pipe({
    name: 'personSearch'
})
export class PersonSearchPipe implements PipeTransform {
    transform(items: Array, searchValue: string){
        if (searchValue){
            return items.filter(item =>{
                if (item.name.indexOf(searchValue) > -1){
                    return true;
                }
                return false;
           })
        }
        else{
            return items;
        }
    }
}

You need to register the PersonSearchPipe to component module like show below

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';

import { AppComponent } from './app.component';
import { PersonSearchPipe } from './personSearch.pipe';
@NgModule({
  declarations: [
    AppComponent,
    PersonSearchPipe
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule
  ],
  providers: [],
  bootstrap: [AppComponent],

})
export class AppModule { }

 

In the HTML for the component add the filter like shown below

personlisthtml

Attached is the source code over here, to run the source please set up angular-cli and do npm install

ES6 + Arrow Function + Mystery with this

We have been using arrow function for quite some time in compile languages like C#, but the same is now available in java script.

An arrow function is short hand, we can leave off the function keyword and we can leave of the return statement. Even though it kind of short hand operator, but its main purposes is to get away from nuances of this keyword in javascript. First we will cover basics around arrow function then discuss nuances around this keyword.
Consider the following example

(function () {
    'use strict'
    var getName = () => "aamol";
    console.log(typeof getName);
})();

What will be the output? It is going to be function, so essentially we are declaring a function but in a short hand way. Now if we execute that function what will be the output, it would be “aamol” 

(function () {
    'use strict'
    var getName = () => "aamol";
    console.log(getName());
})();

So again as mentioned above we can leave off the return keyword in an arrow function, whatever expression is specified over there will get returned. Here is another example of arrow function

(function () {
    'use strict'
    var getName = lastName => "aamol" + " " + lastName;
    console.log(getName("gote"));
})();

So in case if we have one argument to the function then we can leave off the parenthesis. It will output “aamol gote”. Now in case if you have more than 2 parameters then we have 2 use parenthesis. Output would be the same “aamol gote”. 

(function () {
    'use strict'
    var getName = (firstName, lastName) => firstName + " " + lastName;
    console.log(getName("aamol", "gote"));
})();

Now there would be scenarios where you will have more than single expression, then how does the arrow function look like shown below, your arrow function should return some thing.

(function () {
    'use strict'
    var getName = (firstName, lastName) => {
        if (firstName && lastName) {
            return firstName + " " + lastName;
        }
        else if (firstName && !lastName) {
            return firstName;
        }
        else if (!firstName && lastName) {
            return lastName;
        }
        else {
            return null;
        }
    }
    console.log(getName("aamol", "gote"));
})();

As discussed above real purpose of arrow functions is to handle this key word within functions, “this” has always been confusing aspect of JavaScript and in ES6 arrow functions make it easier to understand. Consider following example what would be the output?

    document.addEventListener("click", function () {
        console.log(this)
    });

Output will be “#document” in chrome browser.

Whenever we have an event handler in java script, this gets set to the element that receives the event and this caused problems in ES5 because we could not get access to the context of the function. Now consider the same example with arrow function

'use strict'
document.addEventListener("click", () => console.log(this));

Output will be “#Window” in chrome browser.

We are in the global area over here and not in the context of a function so this refers to the context of code in which we running which is window a global object. So as long as we are using arrow functions this will not be set to the element that is getting the event it is going to be set to the context in the code which are running in.

Lets consider another example,

'use strict'
var person = {
    age: 34,
    firstName: "aamol",
    lastName: "gote",
    getName: function () {
        console.log(this);
    }
}
person.getName();

What would be the output, it would be person object
{age: 34, firstName: “aamol”, lastName: “gote”}

Now we will replace getName function with arrow function

'use strict'
var person = {
    age: 34,
    firstName: "aamol",
    lastName: "gote",
    getName:  () => console.log(this)
}
person.getName();

Output over here would be window object. If we were inside the function then we would get the function context

Lets take another example

'use strict'
var person = {
    age: 34,
    firstName: "aamol",
    lastName: "gote",
    getName: function(){
        return () => console.log(this)
    }
}
person.getName()();

Now in this case getName() is returning the function, so what would be the output, it would be person object, because it getName() is function and that is the context that we are working with and because we are returning the function, so this will be set to the context of invoice object.

Another important aspect for arrow functions is related to .bind, .call and .apply. Consider following example

'use strict'
var person = {
    age: 34,
    firstName: "aamol",
    lastName: "gote",
    getName: function(){
        return () => console.log(this)
    }
}

var person2 = {
    age: 36,
    firstName: "john",
    lastName: "doe",

}
person.getName().bind(person2)();

Output will be {age: 34, firstName: “aamol”, lastName: “gote”} and not person2 object. This is very important with arrow functions you cannot bind a new object to arrow functions. Javascript engine did not even throw the error, it just ignored the bind call. So when u are working with arrow functions you will not be able to change the value of this like in traditional javascript.

Like .bind similar scenario exist for .call and .apply.

'use strict'
var person = {
    age: 34,
    firstName: "aamol",
    lastName: "gote",
    getName: function(){
        return () => console.log(this)
    }
}

var person2 = {
    age: 36,
    firstName: "john",
    lastName: "doe",

}
person.getName().call(person2);

Output will be {age: 34, firstName: “aamol”, lastName: “gote”} and not person2

Same applies to .apply.

So in summary in case of arrow function .call, .bind and .apply are useless, you cannot change the value of this.

One more quirk to the arrow functions consider the following example

'use strict'
var person = {
    age: 34,
    firstName: "aamol",
    lastName: "gote",
    getName: () 
        => console.log(this)
    
}
person.getName();

This is gives an syntax error “Uncaught SyntaxError: Unexpected token =>”
New line character is problem with arrow functions you cannot put the arrow symbol on to the new line.

Arrow functions do not have “prototype” property.

'use strict'
var getName = () => "aamol";
console.log(getName.hasOwnProperty("prototype"));

Output would be false.

Whenever you declare a function in javascript it will by default have the prototype property. So unlike ES% in ES6 if you declare an function with arrow symbol, we do not have access to prototype.

Observable’s in Angular 2 (RxJS)

Observables in Angular 2 can be achieved using RxJS(Reactive Extensions for JavaScript). Observables is an ES7 feature so you need to make use of an external library to use it today. RxJS is a library that allows you to work with asynchronous data streams. So what are asynchronous data streams?

  • Asynchronous – we can call a function and register a callback to be notified when results are available, so we can continue with execution and avoid the Web Page from being unresponsive. This is used for ajax calls, DOM-events, Promises, WebWorkers and WebSockets.
  • Data – raw information in the form of JavaScript data types as: Number, String, Objects (Arrays, Sets, Maps).
  • Streams – sequences of data made available over time. Technically everything is stream.

Observables can help manage async data and a few other useful patterns. Observables are similar to Promises but with a few key differences. The first is Observables emit multiple values over time. For example a Promise once called will always return one value or one error. This is great until you have multiple values over time. Web socket/real-time based data or event handlers can emit multiple values over any given time. This is where Observables really shine. Observables are used extensively in Angular 2.

 Observables  Promise
 Observables handle multiple values over time  Promises are only called once and will return a single value
 Observables are cancellable  Promises are not cancellable

The ability of observables being able to handle multiple values over time makes them a good candidate for working with real-time data, events and any sort of stream you can think of. Being able to cancel observables gives better control when working with in-flow of values from a stream. The common example is the auto-complete widget which sends a request for every key-stroke.

RxJS Observable Promise
Execution  Lazy Eager
Asynchronous  YES YES
Handles data sources that produce ONE value YES YES
Handles data sources that produce MULTIPLE values YES
Debouncing &

Throttling

YES NO
Can be cached YES NO
Can be cancelled YES NO
Retry from failure YES NO

RxJS also provides Observable operators which you can use to manipulate the data being emitted. Some of common operators are:

  • Map
  • Filter
  • Take
  • Skip
  • Debounce
  • Retry

So in angular 2 now you services will start returns observables instead of promises like shown below for category service, getCategories returns an observable.

import { Injectable, Inject } from '@angular/core';
import { Http, Response} from '@angular/http';
import { OpaqueToken } from '@angular/core';

import {Category} from './category';
import {Observable} from 'rxjs/Observable';


export let INTERVIEW_APP_CONFIG = new OpaqueToken('app.config');
export interface ApplicationConfiguration{
    apiEndPoint : string,
    timeOut: number
}

export const INTERVIEW_APP_DI_CONFIG: ApplicationConfiguration = {
  apiEndPoint: 'http://app.cloudapp.net/api/Category',
  timeOut: 20
};


@Injectable()
export class CategoryService {
    categoryServiceUrl :string;
    constructor(private http: Http, @Inject(INTERVIEW_APP_CONFIG) config: ApplicationConfiguration){
        console.log(config.apiEndPoint);
        this.categoryServiceUrl = config.apiEndPoint;
    }
       
    getCategories (): Observable<Category[]>{
        console.log("Get Categories");
        return this.http.get(this.categoryServiceUrl)
                        .map(this.extractCategoryData)
                        .catch(this.handleError);
                        
    } 
    
    private extractCategoryData(res: Response){
        let body = res.json();
        return body || { };
    }
    
    private handleError (error: any) {
        let errMsg = (error.message) ? error.message : 
        error.status ? `${error.status} - ${error.statusText}` : 'Server error';
        console.error(errMsg); // log to console instead
        return Observable.throw(errMsg);
  }
}

An observable is only enabled when a first observer subscribes. This is a significant difference compared to promises. As a matter of fact, processing provided to initialize a promise is always executed even if no listener is registered. This means that promises don’t wait for subscribers to be ready to receive and handle the response. When creating the promise, the initialization processing is always immediately called.

Observables are lazy so we have to subscribe a callback to let them execute their initialization callback. below component defines the subscribe for the observable which has been returned,

import { Component, OnInit } from '@angular/core';
import { Category } from './category';
import './rxjs-operators';
import { CategoryService, INTERVIEW_APP_CONFIG, INTERVIEW_APP_DI_CONFIG } from './categoryService';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  providers:[CategoryService, { provide: INTERVIEW_APP_CONFIG, useValue: INTERVIEW_APP_DI_CONFIG }]
})
export class AppComponent {
  title = 'app works!';
  firstName="Aamol";
  errorMessage: string;
  categories: Category[];
  
 constructor(private categoryService: CategoryService){
   
 }
 ngOnInit(){
   this.getCategories();
   console.log("Getting categories");
  } 
 
 getCategories() {
   this.categoryService.getCategories()
                  .subscribe(
                    categories => this.categories = categories,
                    error => this.errorMessage = error
                  );
 }
}

Observables allow you to register callbacks as shown above, the subscribe method three callbacks as parameters:

  • The onNext callback that will be called when an event is triggered.
  • The onError callback that will be called when an error is thrown.
  • The onCompleted callback that will be called when the observable completes.

Here is the way to register callbacks on an observable:

categoryService.getCategories.subscribe(
  (event) => {
    // handle events
  },
  (error) => {
    // handle error
  },
  () => {
    // handle completion
  }
);

The observable class provides a fromPromise method to create an observable from a promise. This allows you to make a promise part of an asynchronous data stream

Retrying requests – Observable allows you to repeat the source observable sequence the specified number of times or until it successfully terminates. In the context of HTTP requests, this allows you to transparently re-execute requests that failed.

getCategories (): Observable<Category[]>{
        console.log("Get Categories");
        return this.http.get(this.categoryServiceUrl)
                        .retry(4)
                        .map(this.extractCategoryData)
                        .catch(this.handleError);
                        
    } 

Enable RxJS Operators – The RxJS library is quite large. So Angular 2 exposes a stripped down version of Observable in the rxjs/Observable module, a version that lacks most of the operators including map, retry which we have used above, it’s up to us to add the operators we need. We could add every RxJS operators with a single import statement. but we’d pay a penalty in extended launch time and application size because the full library is so big. We only use a few operators in our app.

Instead, we’ll import each Observable operator one-by-one, we’ll put the import statements in one app/rxjs-operators.ts file.

// Statics
import 'rxjs/add/observable/throw';

// Operators
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/debounceTime';
import 'rxjs/add/operator/distinctUntilChanged';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/switchMap';
import 'rxjs/add/operator/toPromise';
import 'rxjs/add/operator/retry';