Angular 2 Service


Angular services are injected using Dependency Injection mechanism and include the values, functions or features.
Service does something. This is for it.

Simple Service Example


import { Injectable } from '@angular/core';

import { Data } from '../data';

const DATA : Data[] = [
    {id:1, name: 'Zuramaru'},
    {id:2, name: 'Ruby'},
    {id:3, name: 'Yohane'}

export class AppService {

    getData() : Promise<Data&#91;&#93;> {
        return Promise.resolve(DATA);

Import Injectable and User @Injectable before class.
This is very simple. Return Promise

How to use this.


import { Component, OnInit } from '@angular/core';

import { Data } from './data';
import { AppService } from './services/app.service';

    selector: 'app',
    template: `Data:<br>
            <li *ngFor="let tmp of array">
                {{}} : {{ }}
    providers: [AppService]

export class ServiceComponent implements OnInit {

    array: Data[];

    constructor(private appService: AppService) { }

    ngOnInit(): void {
        this.appService.getData().then(data => this.array = data);

Import Service class and use provider in component
In ServiceComponent class, use services and keep value as variables. This variable is used in Component.