1

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?

5
  • Off topic, but why do you want to create a stateful service? Services should be stateless and should know nothing about their clients Commented Jul 27, 2017 at 17:06
  • Otherwise how to pass parameters(settings) to service? Service must work with some incoming data is not it? Commented Jul 27, 2017 at 17:11
  • You can't. Consider providing the example that explains what's your case. Yes, it will likely be a variation of factory. Commented Jul 27, 2017 at 17:21
  • Then how to use services right? Is it just set of functions? Does it mean that service can not have constructor? How to put any data in Service then? Commented Jul 27, 2017 at 17:23
  • 1
    @Daniel you would generally configure the service at the module level, with useFactory, not where it's injected. Read angular.io/guide/dependency-injection. Commented Jul 27, 2017 at 17:25

2 Answers 2

1

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);
  }
}
Sign up to request clarification or add additional context in comments.

3 Comments

Where to write this providers: [{ provide: CustomService, useValue: CustomService }]? What does it mean?
It depends on your case. In NgModule or Component. See the manual. useValue means that CustomService will be injected as a class and won't be instantiated by injector.
You can check the answer that uses the same recipe for example.
0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.