Angular 2 Typescript Service

If you want a complete tutorial with live example and step by step please follow the link :

Angular 2 Services

This is just an example to illustrate angular 2 and typescript service.

You find the code source (download) at the end of this tutorial.

Please if it’s your first time here check our hello world (step by step + npm and environment setup) tutorial here.
 

Let’s build our example Car Service.

Step 1:

We create a car interface.

The car in our example is composed of a model, color, doors.

car.ts

/**
 * Created by Tareq Boulakjar.
 */
export interface Car{
    model: string,
    color: string,
    doors: number,
}

Step 2

We create a file that contains some Data ( e.g. 6 cars ).

car-data.ts

/**
 * Created by Tareq Boulakjar.
 */
import {Car} from "./car";

export const CARS: Car[] = [
    {model:'serie 1',color:'red',doors:4},
    {model:'serie 2',color:'red',doors:2},
    {model:'serie 3',color:'black',doors:4},
    {model:'serie 4',color:'red',doors:2},
    {model:'serie 5',color:'white',doors:4},
    {model:'serie 6',color:'white',doors:2},
];

Step 3

create theservice

car.service.ts

/**
 * Created by Tareq Boulakjar.
 */
import {Injectable} from 'angular2/core';
import {CARS} from './car.data';

@Injectable()
export class CarService {
    getCars(){
         return Promise.resolve(CARS);
    }
}

 

Call the service.

 

/**
 * Created by Tareq Boulakjar.
 */
import {Component} from "angular2/core";
import {CarService} from "./car.service"; //1 
import {CarComponent} from "./car.component";
import {Car} from "./car";


@Component({
    selector: "car-list",
    templateUrl: "app/services/cars/car-list.component.html",
    directives: [CarComponent],
    providers:[CarService], //2 
    styleUrls:["app/services/css/app.css"]
})
export class CarListComponent{
    public cars : Car[];

    public selectedCar = {};

    public onModelClick(car){
        this.selectedCar = car;
    }
    constructor(private _carService: CarService){  // 3 
        this.getCars();
    }

    // make a call to our car service
    getCars(){  //4            

          this._carService.getCars().then((cars:Car[])=>this.cars = cars);
    }

}

 

  • In another tutorial we will show you how to optimize the call. In this tutorial we try to keep it easy to understand.

Download – Angular Typescript Service – angulartypescript.com – Code Source