Jorgen
Jorgen

Reputation: 115

Angular standalone component and service constructor injection

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?

Upvotes: 3

Views: 2894

Answers (2)

Eliseo
Eliseo

Reputation: 58019

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;
  }

Upvotes: 1

MGX
MGX

Reputation: 3531

And in main.ts, for bootstrapApplication function call there's ProductsService defined in "providers" section.

No, it should not be there.

The purpose of @Injectable({ providedIn: 'root' }) is to do exactly that. You don't need to declare it in your application bootstrap too.

(reported error: Cannot find name ProductsService)

This one simply means you have not imported the file, so simply import it.

I really do not want to use direct references to service inside of standalone component, nor inject function inside of component.

You have to, that's how it works. If you do not specify what you want to inject, it is impossible for Angular to know what to inject.

Upvotes: 1

Related Questions