Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
328 views
in Technique[技术] by (71.8m points)

angular - Angular:如何在父组件中注入concret类(Angular : How to inject concret class in the parent component)

I have a common component

(我有一个共同的组成部分)

@Component({
  selector: 'mc-common',
  ...
})
CommonComponent {

 constructor(@Optional() @SkipSelf() private readonly merginStrategy: MerginStrategy) {
    if (!this.merginStrategy) {
      this.merginStrategy = new NoopMerginStrategy();
    }
 }
 ...
}

And another component which uses the mc-common

(另一个使用mc-common组件)

@Component({
  selector: 'mc-another',
  template: `
     <mc-commo>
      ...
     </mc-common>
  `,
  providers: [{
    provide: MerginStrategy, useClass: ComplicatedMerginStrategy // or useValue: new ComplicatedMerginStrategy()
  }
})
AnotherComponent {

 constructor(private readonly merginStrategy: MerginStrategy) {

 }
 ...
}

So when I'm calling mc-another , mc-common will take ComplicatedMerginStrategy as instance of MerginStrategy .

(因此,当我致电mc-anothermc-common将把ComplicatedMerginStrategy用作MerginStrategy实例。)

Everything is working fine like this.

(这样一切都很好。)

But what I want to achieve is injecting the same instance of ComplicatedMerginStrategy into AnotherComponent rather than the abstraction but continuing to use the abstraction in the mc-common .

(但是我要实现的是将ComplicatedMerginStrategy同一实例注入AnotherComponent而不是抽象中,而是继续在mc-common使用抽象。)

Something like:

(就像是:)

AnotherComponent {

 constructor(private readonly merginStrategy: ComplicatedMerginStrategy) {

 }
 ...
}

The strategies :

(策略:)

abstract class MerginStrategy {
  merge(a, b): any
}

class NoopMerginStrategy implements MerginStrategy {
   merge(a, b): any {
    return a;
   }
}

class ComplicatedMerginStrategy implements MerginStrategy {
   merge(a, b) {
    ...
   }
}

I hope I'm clear :)

(我希望我很清楚:))

  ask by bubbles translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The solution is useExisting and declare the instance of ComplicatedMerginStrategy before.

(解决方案是useExisting并在之前声明ComplicatedMerginStrategy的实例。)

@Component({
  selector: 'mc-another',
  template: `
     <mc-commo>
      ...
     </mc-common>
  `,
  providers: [
    ComplicatedMerginStrategy, {
    provide: MerginStrategy, useExisting: ComplicatedMerginStrategy
  }]
})
AnotherComponent {

 constructor(private readonly merginStrategy: ComplicatedMerginStrategy) {

 }
 ...
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...