![](/img/trans.png)
[英]How to inject parent component service into dynamic component in Angular?
[英]Angular : How to inject concret class in the parent component
我有一個通用組件
@Component({
selector: 'mc-common',
...
})
CommonComponent {
constructor(@Optional() @SkipSelf() private readonly mergingStrategy: MergingStrategy) {
if (!this.mergingStrategy) {
this.mergingStrategy = new NoopMergingStrategy();
}
}
...
}
另一個使用mc-common
組件
@Component({
selector: 'mc-another',
template: `
<mc-commo>
...
</mc-common>
`,
providers: [{
provide: MergingStrategy, useClass: ComplicatedMergingStrategy // or useValue: new ComplicatedMergingStrategy()
}
})
AnotherComponent {
constructor(private readonly mergingStrategy: MergingStrategy) {
}
...
}
因此,當我調用mc-another
, mc-common
會將ComplicatedMergingStrategy
作為MergingStrategy
實例。
一切都像這樣正常工作。 但是我想要實現的是將ComplicatedMerginStrategy
的相同實例注入AnotherComponent
而不是抽象,而是繼續在mc-common
使用抽象。
就像是:
AnotherComponent {
constructor(private readonly mergingStrategy: ComplicatedMergingStrategy) {
}
...
}
策略:
abstract class MergingStrategy {
merge(a, b): any
}
class NoopMergingStrategy implements MergingStrategy {
merge(a, b): any {
return a;
}
}
class ComplicatedMergingStrategy implements MergingStrategy {
merge(a, b) {
...
}
}
我希望我很清楚:)
解決方法是useExisting
並在之前聲明ComplicatedMerginStrategy
的實例。
@Component({
selector: 'mc-another',
template: `
<mc-commo>
...
</mc-common>
`,
providers: [
ComplicatedMerginStrategy, {
provide: MerginStrategy, useExisting: ComplicatedMerginStrategy
}]
})
AnotherComponent {
constructor(private readonly merginStrategy: ComplicatedMerginStrategy) {
}
...
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.