Services in angular
What is a service
Service is a predefined business logic , that can handle specific functionality.
Technically service is a collection of factories and every factory is a collection of related type of function.
A factory implements a single call mechanism where an object is initialized every time when a functionality is required.
Service uses a singleton mechanism where object is initialized only once and through the object it gives
access to functions.
A service follows dependency Injection, which is a software design pattern used for creating reusable, main table and testable components.
Angular services are implemented from "Injectable " Module which uses @Injectable() meta data.
Example
myservice.ts
import { Observable } from "rxjs";
import {
Injectable
} from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class Myservice {
getprods()
{
let obj=new Observable((observer)=>{
//write unit of code for async exec
let prods:string[]=["htc","samsung","dell"];
observer.next(prods);
observer.complete();
});
return obj;//returning observable object to a
//component,
//component will register callback funcs to observable using subscribe
//method,this callback funcs can be called using observer.next,..
}
Testclick() {
console.log('Test Click');
}
}
Component.ts changes
import { Component, OnDestroy, OnInit } from '@angular/core';
import { Myservice } from './myservice';
@Component({
selector: 'app-observabledemo',
templateUrl: './observabledemo.component.html',
styleUrls: ['./observabledemo.component.css']
})
export class ObservabledemoComponent implements OnInit,OnDestroy {
obj:Myservice;
obsref:any;
prods:any | undefined;
constructor() {
this.obj=new Myservice();
}
ngOnInit():void
{
this.obsref=this.obj.getprods().subscribe(data => this.prods = data);
}
ngOnDestroy(): void
{
this.obsref.unsubscribe();
}
TestClickMsg() {
this.obj.Testclick()
}
}
.html Changes
Step by Step Explanation
1 Create a service
2 Register a service
3 Inject a service
import {
Injectable
} from '@angular/core';
@Injectable({
providedIn: 'root'
})
Example
service.ts
getAPIData() {
let obj=new Observable((observer)=>{
//write unit of code for async exec
let apidata: any=[{
"id": 1,
"first_name": "Test",
"last_name": "Uday 1"
}, {
"id": 2,
"first_name": "Test",
"last_name": "Uday 2"
}, {
"id": 3,
"first_name": "Test",
"last_name": "Uday 3"
}];
observer.next(apidata);
observer.complete();
});
return obj;
}
component.ts
import { Myservice } from './myservice';
@Component({
selector: 'app-observabledemo',
templateUrl: './observabledemo.component.html',
styleUrls: ['./observabledemo.component.css']
})
export class ObservabledemoComponent implements OnInit,OnDestroy {
obsref:any;
apidata:any | undefined;
constructor(private Data: Myservice) {
}
ngOnInit():void
{
this.obsref=this.Data.getAPIData().subscribe(data => this.apidata = data);
}
ngOnDestroy(): void
{
this.obsref.unsubscribe();
}
TestClickMsg() {
this.Data.Testclick()
}
}
.html Changes