- Services are mostly used in displaying datas from APIs
- To generate a new service use ng generate service Services/SERVICE_NAME
- services are injectable because they would be mostly called by other components
- Injection of services can happen at three level
- AppModule – Same Instance of Service Injected would be available across application
- AppComponent – Same Instance of Service Injected at this level would be available in this component and all child component
- Any Other Component – Same Instance of Service Injected would be available to this component and child component(not to parent component)
- @Injectable is not needed if the Service is added in app.modules.ts
aboutus.component.ts
.
.
constructor(private objApi:ApiService) {
this.objApi.getDataFromRest();
}
.
.
api.service.ts
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class ApiService {
constructor() { }
getDataFromRest()
{
return console.log("Data from Rest Method");
}
}