Angular docs say that Self is Parameter decorator to be used on constructor parameters, which tells the DI framework to start dependency resolution from the local injector.
If I have a component like this
@Component({
selector: 'app-foo',
templateUrl: './foo.component.html',
styleUrls: ['./foo.component.scss'],
providers: [BarService],
})
export class FooComponent {
constructor(public barService: BarService) {}
}
Though I provided BarService in root injector, FooComponent will inject its own instance of service because it's in the Components providers list. And it will work without @Self().
Clearly, I'm missing something because I can't imagine in which scenarios @Self() can be used.
I've read numerous articles on resolution modifiers but still, it is not clear to me what are the use cases of @Self()
@Self() means the component need to provide it's own instance.
When you have @Self, even if the root injector has a reference, an exception will be thrown is the component doesn't provide its own instance of the service.
This is to ensure that instance does not depend from the parents.
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