For example if I register a service in app.module.ts
I have to do the following to make a service available in a component
app.module.ts
import { AppComponent } from './app.component';
import { MyComponent } from './mycomponent/mycomponent.component';
import { MyService } from './services/myservice.service';
@NgModule({
declarations: [
AppComponent,
MyComponent
],
imports: [
],
providers: [MyService],
bootstrap: [AppComponent]
})
mycomponent.component.ts
import { Component, OnInit } from '@angular/core';
import { MyService } from '../services/myservice.service';
@Component({
selector: 'my-selector',
templateUrl: './mycomponent.component.html',
styleUrls: ['./my-component.component.scss']
})
export class MyComponent implements OnInit {
constructor(private _myService: MyService) { }
ngOnInit() {
this._myService.test()
}
}
But I could also just register in the component itself to use it without having to add anything to app.module.ts
import { Component, OnInit } from '@angular/core';
import { MyService } from '../services/myservice.service';
@Component({
selector: 'my-selector',
templateUrl: './mycomponent.component.html',
styleUrls: ['./my-component.component.scss'],
providers: [MyService]
})
export class MyComponent implements OnInit {
constructor(private _myService: MyService) { }
ngOnInit() {
this._myService.test()
}
}
I am curious, what is the difference for each way?
Registering a Service in a Component Notice that in the providers array of the component, the service is registered and then consumed in the constructor of the component. This way, the service will not be used by any other component, directive, or pipe in the whole app.
To limit the scope of a service to only its component, you should register it with the component's provider array.
We can list components, directives, and pipes, which are part of the module, in the "declarations" array. We can import other modules by adding them to the "imports" array. We can list down all the services which are part of our module in the "providers" array.
Services in Angular are simply typescript classes with the @injectible decorator. This decorator tells angular that the class is a service and can be injected into components that need that service. They can also inject other services as dependencies.
When you add your service in the root providers of your application, all components will inject the same instance of the service. So only one instance will be created during the application. In this case you can keep state
in your service.
When you add your service in the providers of your Component
, every time a new instance of that component will be created, new instance
of service also will be created. In this case you can't keep state
in this type of service,
Depending on your logic provide where you need, but it's common case to provide all services in the root module.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With