Angular Service 1 – Service

Service

Service is Angular prepared DI module.
Like spring or other DI support framework, Angular is also support several level Injectable.
To add Injectable annotation, the class support injectable module.

Sample 1 – Module Level Inject

Module level inject means that adding service into module.ts

simpleservice.service.ts

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

@Injectable()
export class SimpleService {
  created: Date;

  constructor() {
    this.created = new Date();
  }

  show() {
    return this.created.toLocaleString();
  }
}

simpleservice.component.ts

import { Component } from '@angular/core';
import { SimpleService } from './simpleservice.service';

@Component({
  selector: 'app-root',
  template: `
    <div>SimpleService : {{current}}</div>
  `
})
export class SimpleServiceComponent {
  current: string;

  constructor(private simpleService: SimpleService) {
    this.current = simpleService.show();
  }
}

app.module.ts

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';

import { SimpleService } from './simpleservice.service';
import { SimpleServiceComponent } from './simpleservice.component';

@NgModule({
  imports: [
    CommonModule,
    BrowserModule,
    FormsModule
  ],
  declarations: [
    SimpleServiceComponent
  ],
  providers: [ SimpleService ],
  bootstrap: [
    SimpleServiceComponent
  ]
})
export class AppModule {}

Sample 2 – Local level Inject

Local level inject means that import service only the component you want to import
Service is not declared in app.module.ts(module file)

local/localservice.service.ts

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

@Injectable()
export class LocalService {
  created: Date;

  constructor() {
    this.created = new Date();
  }

  show() {
    return this.created.toLocaleString();
  }
}

localservicecomponent.ts

import { Component } from '@angular/core';
import { LocalService } from './local/localservice.service';

@Component({
  selector: 'app-root',
  providers: [
    {provide: LocalService, useClass: LocalService}
  ],
  template: `
    <div>LocalService : {{current}}</div>
  `
})
export class LocalServiceComponent {
  current: string;

  constructor(private localService: LocalService) {
    this.current = localService.show();
  }
}