Can Injectable Services have a providers list?

Issue

I was doing some code with a component class and a service class.

@Injectable()
class MyService extends Object {
  ...
}

@Component(
  ...
  providers: const [MyService]
)
class myCompoment implements onInit {
  final MyService _service;
  MyComponent(this._service);
  ...
}

Is there a way to say, give a provider to my injectable service such that it can consume? When looking online, it had shown that Component comes from Injectable, so I was thinking to create a component out of the service, but that doesnt quite make sense as to me a component would also have UI.

Ideally, I wanted to do something like:

@Injectable()
class AnotherClass {}

@Injectable(providers: const [AnotherClass])
class MyService extends Object {
  ...
}

@Component(
  ...
  providers: const [MyService]
)
class myCompoment implements onInit {
  final MyService _service;
  MyComponent(this._service);
  ...
}

but Injectable doesnt allow the providers property it seems.

Solution

You can add providers: const [MyService, AnotherClass] to components and MyService can inject AnotherClass by just listing it as constructor parameter

@Injectable()
class AnotherClass {}

@Injectable()
class MyService extends Object {
  final AnotherClass _anotherClass;

  MyService(this._anotherClass);
}

@Component(
  ...
  providers: const [MyService, AnotherClass]
)
class myCompoment implements onInit {
  final MyService _service;
  MyComponent(this._service);
  ...
}

Answered By – Günter Zöchbauer

Answer Checked By – Cary Denson (FlutterFixes Admin)

Leave a Reply

Your email address will not be published.