I'm having problem injecting a service through standalone component's constructor.
Service is defined as Injectable with provider set to root:
@Injectable({ providedIn: 'root' }) export class ProductsService {...}
And in main.ts, for bootstrapApplication function call there's ProductsService defined in "providers" section.
This should be enough to be able to inject ProductsService singleton in component's constructor, yet it's not being recognized there (reported error: Cannot find name ProductsService).
I really do not want to use direct references to service inside of standalone component, nor inject function inside of component.
What am I missing here?
I imagine you can make a work-around: create a singleton service in the way
export interface ServiceInterface{
..definition of your interface..
}
export class SingletonService{
private static instance: ServiceInterface;
public static getInstance(): ServiceInterface{
if (!SingletonService.instance) {
getInstance.instance = new FoolService() as ServiceInterface;
}
return SingletonService.instance;
}
}
To "import" the service in a component you use some like:
foolService!:ServiceInterface
constructor() {
this.foolService=SingletonService.getInstance()
}
Now, if you want to change the function getService in SingletonService
public static getInstance(): ServiceInterface{
if (!SingletonService.instance) {
//return "AnotherService"
getInstance.instance = new AnotherService() as ServiceInterface;
}
return SingletonService.instance;
}