Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

angular - Inject all Services that implement some Interface

Simple scenario:

I have multiple Services that implement a common Interface. All those Services are registered within the bootstrap method.

Now I'd like to have another Service, which injects all registered Services that implement the common Interface.

i.e.

export interface MyInterface {
    foo(): void;
}

export class Service1 implements MyInterface {
    foo() { console.out("bar"); }
}

export class Service2 implements MyInterface {
    foo() { console.out("baz"); }
}

export class CollectorService {
    constructor(services:MyInterface[]) {
        services.forEach(s => s.foo());
    }
}

Is that possible somehow?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

You need to register your service providers like this:

boostrap(AppComponent, [
  provide(MyInterface, { useClass: Service1, multi:true });
  provide(MyInterface, { useClass: Service2, multi:true });
]);

This will work only with classes not with interfaces since interfaces don't exist at runtime.

To make it work with interfaces, you need to adapt it:

bootstrap(AppComponent, [
  provide('MyInterface', { useClass: Service1, multi:true }),
  provide('MyInterface', { useClass: Service2, multi:true }),
  CollectorService
]);

and inject this way:

@Injectable()
export class CollectorService {
  constructor(@Inject('MyInterface') services:MyInterface[]) {
    services.forEach(s => s.foo());
  }
}

See this plunkr for more details: https://plnkr.co/edit/HSqOEN?p=preview.

See this link for more details:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...