0
votes

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

1 Answers

2
votes

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.