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...

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...