Services in Angular 2

Making services in Angular 2 is pretty easy. Services help us keep our angular code clean so that we don’t have to keep rewrite the same functions for different pages. It gives us access to functions that we can inject into multiple components throughout our application. We can create one like in side of our project like so:

$ mkdir services
$ cd services
$ touch packs.services.ts

For our packs services, we want to write some functions that get and post data to and from the database through our server. Let import the Injectable decorator and export our new service class.

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';
@Injectable()
export class PackService {
  constructor(public http: Http) {}
}

The injector allows us to use PackService as a dependency injection in other component. Lets create a method that will talk to our server and get the data we want. This will require importing HTTP to communicate with the server.

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';
@Injectable()
export class PackService {
  constructor(public http: Http) {}
  public getPacks(cb) {
this.http.get(`${this.SERVER_URL}/packs`)
.map((res) => res.json())
.subscribe(({data}) => {
cb(data);
}, (err) => {
console.error(err);
});
});
}
}

Now our method will be available four use where ever we see fit. All we have to do it import this class in any component and invoke the function.

import { Component } from '@angular/core';
import { NavController, NavParams} from 'ionic-angular';
import { PackService } from "../../services/pack.service";
@Component({
selector: 'page-packs',
templateUrl: 'packs.html',
})
export class Packs {
public packNames: any;
  constructor(public navCtrl: NavController, 
public navParams: NavParams,
public modalCtrl: ModalController,
public pkSvs: PackService) {}
  public ionViewDidEnter() {
this.pkSvs.getPacks(this.newPacks.bind(this));
}

Using services is a great way to keep lengthy methods from cluttering your components and keeps your code DRY and functional all around.