4/14/16

Events In Angular2

Like in angular1 you can use events in angular2. What events good for? To make distant components to notify one to another.

How to send event

Everybody knows that for sending event you need to create some kind of channel. This channel will be used to publish(emit) event and to subscribe to event for getting notified . Angular2 has its own EventEmitter class just for this scenario


import {Injectable, EventEmitter} from 'angular2/core';
@Injectable()
export class EmitterService {
  private static _emitters: { [channel: string]: EventEmitter } = {};
  static get(channel: string): EventEmitter {
    if (!this._emitters[channel]) 
      this._emitters[channel] = new EventEmitter();
    return this._emitters[channel];
  }
}

This service sets some channel (if no channel exists) and stores it in the private member

Challenge

In this post i want to demonstrate usage of events by bulding a refresh chart button, of the panel on which a flot component from older posts is located.
pressing on this button should refresh the data of the chart in the child flot component.

Click Event

Sending and catching click event is pretty straightforward:
Sending


<a href="#" panel-refresh="" (click)="chartRefresh();false">
    <em class="fa fa-refresh"></em>
</a>

Catching

  ...
  chartRefresh(){
   this.getEntries();
  }
  ...

The problem is to send custom event from parent component panel
to its child conmponent flot that will cause chart to redraw itself.
This event must be fired after data loaded through ajax request.


  ...
    this.f.getFlotEntries()
      .subscribe(entries => {
        //here event is emitted
        this.e.emit('Broadcast');
      },
  ...

Full Code Of Panel Component


import {Component} from 'angular2/core'
import {FlotCmp} from './flot';
import {FlotService} from './FlotService';
import {EmitterService} from './EmitterService';
import {Observable}     from 'rxjs/Observable';
import {HTTP_PROVIDERS}    from 'angular2/http';
import {Http, Response} from 'angular2/http';
@Component({
  selector: 'panel',
  providers: [],
  template: `
 <div class="panel panel-default">
    <h2 class="panel-heading">
    <div class="pull-right">
    <a href="#" panel-refresh="" (click)="chartRefresh();false"><em class="fa fa-refresh"></em></a>
    </div>
    <div>panel heading</div>
    </h2>
    <flot class="panel-body" height="250px" width="100%"></flot>
 </div>
  `,
  directives: [FlotCmp], 
  providers: [
    FlotService,
    EmitterService,
    HTTP_PROVIDERS
  ] 
})
export class Panel {
  
  constructor(private f:FlotService,private e:EmitterService) {
    
    this.e = EmitterService.get("channel_1"); 
    this.getEntries();
  }
  getEntries(){
    this.f.getFlotEntries()
      .subscribe(entries => {
        //here event is emitted
        this.e.emit('Broadcast');
      },
      error =>  {
        this.errorMessage = error;
         console.log(error);
      });    
    
  }
  chartRefresh(){
   this.getEntries();
  }
}

Handling event

Child component flot responding to custom event from its parent.


   ...
   this.emitter.subscribe(msg => {      
       $.plot( plotArea, this.dataset, this.options);
   });
   ...

3/27/16

Using Promises In Angular2

In the last post we created our first angular service. This service served only some static data for chart componentt we build in previous posts.
Everybody knows that to serve static data is not cool.
The really though guys use services for bring data from server.
In other words - real service must use is promises.

Promises In Angular2

For one who used promises in angular 1. to use promise in angular2 is pretty simple:


@Injectable()
export class FlotService {
  getFlotEntries() {
    return Promise.resolve(FlotEntries);
  }
}

Yes, the same old good Promise.resolve. And for consume the service we should use the same old "then"

export class App implements OnInit {
  
  private dataset:any;
  public entries;  
  getEntries() {
    this._flotService.getFlotEntries().then(
                       entries => this.dataset[0].data = entries,
                       error =>  this.errorMessage = error);
  } 

Now lets make our chart component to work with this service.

Projecting data into component

The issue i had run into is that while the call to the service is on the main "App" component, the place i want data to be displayed is on the inner component - "Flot", which getting chart "data" property as input parameter:


<flot  [options]="splineOptions" [dataset]="dataset" height="250px" width="100%"></flot>

In angular 1. all data changes are observed and immediately projected after the change is located by digest cycle.
In angular2 - not in all cases. Angular2 change detection doesn't observe the content only the value or reference itself (angular2 observes only "dataset" but not inner property "data")

A workaround

One way to make angular2 to watch the inner properties changes is to use ngDoCheck().
ngDoCheck() is called every change detection cycle, whether or not there are any input property changes.(great thanks to these guys for this information)
Now we need to modify flot component - so it start to use OnChanges:


import {Component, ElementRef, Input} from 'angular2/core';

@Component({
  selector: 'flot',
  template: `
loading
` }) export class FlotCmp{ ... ngOnInit() { if(!FlotCmp.chosenInitialized) { let plotArea = $(this.el.nativeElement).find('div').empty(); plotArea.css({ width: this.width, height: this.height }); $.plot( plotArea, this.dataset, this.options); FlotCmp.chosenInitialized = true; } } ngDoCheck() { if(this.dataset[0].data !== null && !this.dataPlotted) { console.log('plotting data'); let plotArea = $(this.el.nativeElement).find('div').empty(); $.plot( plotArea, this.dataset, this.options); this.dataPlotted = true; } } }
Now the child component view reacts to changes of flot data

Here is running code: Hope you have fun reading...

2/23/16

Using Angular2 Services

Remember we created flot component in previous posts?
Lets have a quick look on the code now:


export class App {  
  constructor() {
    ...
    //Look here - dont you feel something here is uuuugggglllyyyy?
    this.dataset = [{label: "line1",color:"blue",data:[
    [1, 130],
    [2, 40],
    [3, 80],
    [4, 160],
    [5, 159],
    [6, 370],
    [7, 330],
    [8, 350],
    [9, 370],
    [10, 400],
    [11, 330],
    [12, 350]
]}];
  }
}

The way dataset property sat - is perfect example of hardcoding, and everybody knows that hardcoding is bad.
Since we dont have real server to get data from yet, at least lets move the data-getting logic to some different module, in other words -

Lets Create A Service


export var FlotEntries: Array[] = [
    [1, 130],
    [2, 40],
    [3, 80],
    [4, 160],
    [5, 159],
    [6, 370],
    [7, 330],
    [8, 350],
    [9, 370],
    [10, 400],
    [11, 330],
    [12, 350]
];

//@Injectable()
export class FlotService {
  getFlotEntries() {
    return FlotEntries;
  }
}

This service doing only one thing - getting data for a plot chart.

Lets Use Our Service

Last thing that left - is to teach our main component how to use the service:
Note: Dont forget to list the service inside "poviders" property


//our root app component
import {Component} from 'angular2/core'
import {FlotCmp} from './flot';
import {FlotService} from './FlotService';

@Component({
  selector: 'my-app',
  providers: [],
  template: `
    <div>
      <flot  [options]="splineOptions" [dataset]="dataset" height="250px" width="100%"></flot>
    </div>
  `,
  directives: [FlotCmp],
  providers: [FlotService]//important!!!
})
export class App {
  
  constructor(private _flotService:FlotService) {
    this.name = 'Angular2'
    this.splineOptions: any = {
            series: {
                lines: { show: true },
                points: {
                    radius: 3,
                    show: true
                }
            }
    };
    this.dataset = [{label: "line1",color:"blue",data:this._flotService.getFlotEntries()]}];
  }
}


Looks better isn't it?
plunkr
Thats it, now you know how to create angular2 service.
Hope you have fun reading

Getting started with docker

It is very simple to get started usig docker. All you need to do-is download the docker desktop for your system Once you get docker syste...