My service setup includes a base service and two services that inherit from it:
@Injectable({ providedIn: 'root' })
export class BaseService {
foo(src?: string){
return `speaking from ${src || 'BaseService'}`;
}
}
@Injectable({ providedIn: 'root' })
export class SomeService extends BaseService {
foo(){
return super.foo('SomeService')
}
}
@Injectable({ providedIn: 'root' })
export class AnotherService extends BaseService {
foo(){
return super.foo('AnotherService')
}
}
I want to inject these services into a component and get instances of all three classes:
@Component({
selector: 'my-app',
template: `
<div>
<p>Who's there?</p>
<p>{{ base }}</p>
<p>{{ some }}</p>
<p>{{ another }}</p>
</div>
`,
})
export class App {
base: string;
some: string;
another: string;
constructor(base: BaseService, some: SomeService, another: AnotherService) {
this.base = base.foo();
this.some = some.foo();
this.another = another.foo();
}
}
Instead, I am getting three instances of the same class (HTML output):
Who's there?
speaking from BaseService
speaking from BaseService
speaking from BaseService
- Why is this happening?
- Why are SomeService, AnotherService and BaseService not considered unique tokens for Angular Dependency Injection?
It appears that adding
...
{ provide: SomeService , useClass: SomeService },
{ provide: AnotherService , useClass: AnotherService },
...
in the providers will resolve the issue.
- Why is this explicit declaration necessary?
A plnkr demonstrating the issue: