Daniel
Daniel

Reputation: 1755

Passing parameters to constructor of a service using Dependency Injection?

I have custom service class:

@Injectable()

export class CustomService {
  constructor(num: number) {
  }
}

This class is injected in constructor of component like this:

constructor(private cs: CustomService) {
}

But how to pass parameter num to service in constructor described above? Something like that:

constructor(private cs: CustomService(1)) {
}

I know as solution I can use Fabric pattern, but is there only one way to do that?

Upvotes: 1

Views: 650

Answers (2)

Estus Flask
Estus Flask

Reputation: 223114

If CustomService instances should not be injector singletons, it is:

providers: [{ provide: CustomService, useValue: CustomService }]

...

private cs;

constructor(@Inject(CustomService) private CustomService: typeof CustomService) {
  this.cs = new CustomService(1);
}

If CustomService is supposed be memoized to return singletons for respective parameter, instances should be retrieved through additional cache service:

class CustomServiceStorage {
  private storage = new Map();

  constructor(@Inject(CustomService) private CustomService: typeof CustomService) {}
  get(num) {
    if (!this.storage.has(num))
      this.storage.set(num, new this.CustomService(num));

    return this.storage.get(num);
  }
}

Upvotes: 1

DeborahK
DeborahK

Reputation: 60596

A service can hold data. You could define a public property in your service and set that data.

Here is an example:

import { Injectable } from '@angular/core';

@Injectable() 
export class DataService {
  serviceData: string; 
}

But if you are configuring the service, Jon's comment to your question may be a better solution.

Upvotes: 0

Related Questions