As you build your application, you will create services. An Angular component is to contain logic for the view, while services contains logic for the component. For example, a call to an API to get data is one example a job that a services performs. This is where providers come in.
Services get injected into a component to give the component access to the functionality the service provides. There are a couple of ways to inject the service into the application component.
In the provider array…
@NgModule({
declarations: [
AppComponent
],
imports: [
CommonModule,
CoreModule,
FormsModule
],
providers: [
AppService
]
})
You can also import it into the component itself…
// Import service
import { DataService } from '../Services/data.service';
// Place import in constructor variable
// Can use dataService variable in code
constructor(
private dataService : DataService
) {
You will find yourself doing this a ton in your Angular apps. So it will probably become second nature to you.
Happy Coding!
Clay Hess