Angular 2 Service
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
services/app.service.ts
import { Injectable } from '@angular/core';
import { Data } from '../data';
const DATA : Data[] = [
{id:1, name: 'Zuramaru'},
{id:2, name: 'Ruby'},
{id:3, name: 'Yohane'}
];
@Injectable()
export class AppService {
getData() : Promise<Data[]> {
return Promise.resolve(DATA);
}
}
Import Injectable and User @Injectable before class.
This is very simple. Return Promise
How to use this.
service.component.ts
import { Component, OnInit } from '@angular/core';
import { Data } from './data';
import { AppService } from './services/app.service';
@Component({
selector: 'app',
template: `Data:<br>
<ul>
<li *ngFor="let tmp of array">
{{tmp.id}} : {{ tmp.name }}
</li>
</ul>
`,
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.
