我有一个基本服务和两个继承服务:
@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')
}
}
我希望将它们注入某些组件并检索三个单独类的实例:
@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();
}
}
相反,我得到了三个相同类的实例(HTML输出):
Who's there?
speaking from BaseService
speaking from BaseService
speaking from BaseService
似乎推杆
...
{ provide: SomeService , useClass: SomeService },
{ provide: AnotherService , useClass: AnotherService },
...
提供者中的将使其起作用。
答案 0 :(得分:1)
SomeService
和AnotherService
继承了BaseService
的装饰器元数据,因此angular在其位置注入了BaseService
的实例。
这很危险,因为从SomeService
继承而来的AnotherService
或BaseService
中调用任何实例成员都会触发运行时错误。
归档所需行为的最简单方法是从没有装饰器的通用抽象基类继承:
export abstract class AbstractBaseService {
foo(src?: string) {
return `speaking from ${src || 'AbstractBaseService'}`;
}
}
@Injectable({ providedIn: 'root' })
export class BaseService extends AbstractBaseService {
foo() {
return super.foo('BaseService');
}
}
@Injectable({ providedIn: 'root'})
export class SomeService extends AbstractBaseService {
foo() {
return super.foo('SomeService');
}
}
@Injectable({ providedIn: 'root' })
export class AnotherService extends AbstractBaseService {
foo() {
return super.foo('AnotherService');
}
}
我modified your plnkr测试了这种方法。