Hopefully, someone will point me to the right direction here. I need some help in getting DI working with my angular services. I have the following code where my angular services are currently singleton.
export interface IMyHandler {
run(): void;
}
@Injectable({
providedIn: 'root'
})
export class MyHandler1 implements IMyHandler {
private somethingElse = inject(SomeOtherClass);
constructor() {
}
public run(): void {
}
}
@Injectable({
providedIn: 'root'
})
export class MyHandler2 implements IMyHandler {
private somethingElse = inject(SomeOtherClass);
constructor() {
}
public run(): void {
}
}
@Injectable({
providedIn: 'root'
})
export class LookupService {
private customHandlersMap: Map<string, IMyHandler> = new Map<string, IMyHandler>();
constructor() {
this.customHandlersMap.set('M1', inject(MyHandler1));
this.customHandlersMap.set('M2', inject(MyHandler2));
}
public getHandlerByName(key: string) : IMyHandler {
return this.customerHandlersMap.get(key);
}
}
@Component({
templateUrl: './some.component.html',
styleUrls: ['./some.component.scss']
})
export class MyComponent {
constructor(private lookupService: LookupService) {
}
public callHandler(key: string) {
this.lookupService.getHandlerByName(key).run();
}
}
The above creates service as singleton. What I need is when I call MyComponent.callHandler() method, it gets me new instance of the class from the lookupService and then simply calls run() method on it. I tried using providers:
in MyComponent declaration, but it didn’t seem to work, and also I don’t want to list all IMyHandler instances there.