0

I have a simple factory and an injection token which I use in Angular dependency injection like this:

const TOKEN = new InjectionToken<EventEmitter<MyType>>("Create p");

and the factory:

const createEventEmitter = () => new EventEmitter<MyType>();

Now I provide it in my module like so:

providers: [
 {provide: TOKEN, useFactory: createEventEmitter}]

And I inject it in some constructor:

constructor(@Inject(TOKEN) emitter: EventEmitter<MyType>)

This works. However, I do get a singleton instance.

What if I want to do this like the factory pattern, so that I get a new instance whenever I inject a reference? Is this possible? Kinda like Spring's @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE).

Bonus question: Is it possible to create an injector token that injects a new instance of a class with a generic type parameter? So one injector token that injects all EventEmitter.

1 Answer 1

2

The key there is the module where you are providing if you provide on app.module it is going to be a singleton but if you provide in a custom component you will have same number of instances of components and injection class.

@Component({
  selector: 'custom',
  templateUrl: './custom.component.html',
  styleUrls: ['./custom.component.scss'],
  provider:[{provide: TOKEN, useFactory: createEventEmitter}]
})

If you have a child module you can do it too.

Sign up to request clarification or add additional context in comments.

5 Comments

I do this now. It works, but it is a bit cumbersome, because I need to repeat the same lines over and over again. Is this recommended? Or is it recommended to build a service that has factory methods which I then can call in my components?
Yes I use it as a service.
Did you get a solution for your problem?
I do it on component level now. However, I am still trying to figure out a better way though. While a factory service provides a lot of flexibility, it is not really an ideal solution either.
Is there some update regarding this? looking for something similar too.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.