For example, if I register a service with app.module.ts
, I must do the following to make the service available in the 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 just register in the component itself to use it without adding 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 path?
source
share