Angular Service 2 – Injector
Injector
Create instance to use get method.
For other injection, please see Angular Service 1
Service
simpleservice.service.ts
import { Injectable } from '@angular/core';
@Injectable()
export class SimpleService {
created: Date;
constructor() {
this.created = new Date();
}
show() {
return this.created.toLocaleString();
}
}
Use injector in Component
injector/injector.component.ts
import { Component, Injector } from '@angular/core';
import { SimpleService } from '../simpleservice.service';
@Component({
selector: 'app-root',
template: `
<div>Injector : {{current}}</div>
`
})
export class InjectorComponent {
current: string;
constructor(private injector: Injector) {
const service = this.injector.get(SimpleService);
this.current = service.show();
}
}
Set Injector in constructor, and call get method to make service instance.
This service instance can call method in Service class.
