What Is Service In Angularjs 2
Hello everybody,
today I want to write few words about AngularJS 2 services, or if to be more specific what is Service in angular at all? If to speak very very shortly: Service - it's a class with focused purpose independent from any particular component. It can be caching purpose, or logging purpose, or sending http requests purpose.
Lets say you need to build a service in AngularJS 2. You'll need to go through the following steps:
- Create class for service
- Define metadata with decorator
- Import what is needed for service
import { Injectable } from '@angular/core'
@Injectable() //needed if we have injected dependency or for consistency
export class StudentsService{
getStudents() : IStudent[]{
}
}
One more important detail about Services. As usually services have lifetime as singletons. Why I say as usually? Because you can have two or even more instances of service, if you register them in parallel components. Then Angular will crate two instances of your service. It's not nesessary bad. It's just something that you maybe not expect to receive.