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