【发布时间】:2019-02-26 13:07:33
【问题描述】:
我有一个基础服务和两个继承服务:
@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
- 为什么这不起作用?
- 为什么 SomeService、AnotherService 和 BaseService 不是 Angular DI 的唯一标记?
好像放了
...
{ provide: SomeService , useClass: SomeService },
{ provide: AnotherService , useClass: AnotherService },
...
在提供程序中将使其工作。
- 为什么明确需要这样做?
【问题讨论】:
-
这只是 OOP 的概念
-
想解释一下它是否如此简单? ;)
-
您的评论毫无意义。如果您认为自己对 OP 问题有答案,请添加。
标签: javascript angular typescript inheritance dependency-injection