1

I have a service named HeaderService(header.service.ts) which takes URL as a constructor parameter and has method getManifest which returns a JSON. Now, the JSON has an array of URLs. I have to hit those URLs and getManifest for them. Now, for each corresponding URL, I was planning to create a seperate HeaderService instance and then call getManifest but it turns out Angular 6 doesn't provide that functionality (I come from Java background and I was thinking a bit like in Java). So, how do I create instances of HeaderService dynamically? Note that I cannot do it at the time of injection and hence the factory option seems to be not useful here to me.

Also, I would prefer not to change the code of HeaderService as it is generated use Swagger CodeGen and second, I writing a getManifest(URL: string) in some other class (say, service.util.module.ts) will cause code duplication.

Note: I have referred to previously posted questions (like this one) but they discuss how to create multiple instances at the time of injection. My case is different.

Nikhil Chilwant
  • 629
  • 3
  • 11
  • 31
  • 1
    Simply not decorate them with `@Injectable`, they become casual classes that you can instantiate with `new MyService` ? –  Nov 05 '18 at 11:29
  • Your injectable Service could be like a Java factory maybe? Map each URL from your array to an instance that gets passed your injected parameters – Nigel Nop Nov 05 '18 at 11:50

1 Answers1

0

I think you just need to create that service as a new object (at the end is a simple class) and do what you need to with it, let me put an example to be clearer:

const service = new HeaderService('originalURL');
service.getManifest().forEach(url => new HeaderService(url));

I am not sure what you need to do exactly with it, if you need to do more things instead of using arrow function just use the brackets and place the logic.

Another thing is, if you need to call a method which returns an observable, you can transform them into promises and run them all in parallel or as observables too:

// Promises way
const promises = service.getManifest().map(url => new HeaderService(url).doSomething().toPromise());
Promise.all(promises).then(.....

// Observable way
import { forkJoin } from 'rxjs';
...
const observables = service.getManifest().map(url => new HeaderService(url).doSomething());
forkJoin(observables).subscribe(result => ....

Some links:

https://developer.mozilla.org/es/docs/Web/JavaScript/Referencia/Objetos_globales/Promise/all

https://www.learnrxjs.io/operators/combination/forkjoin.html

Alejandro Lora
  • 7,203
  • 3
  • 18
  • 34