0

I'm very to Angular and I want to figure out how can I pass parameters to an object constructor that is being injected into a component.

Here is an example:

image-capture.service.ts

@Injectable({ providedIn: 'root'})
export class ImageCapture {

  constructor(
    private sdk: any,
    private videoSource: HTMLVideoElement,
    private cameraFeedback: HTMLCanvasElement) {}
}

image-scanner.component.ts

@Component({
  selector: 'app-document-scanner-component',
  templateUrl: './app-document-scanner-component.html',
  styleUrls: ['./app-document-scanner-component.scss'],
})
export class ImageScannerComponent {

  @ViewChild('video') video!: ElementRef<HTMLVideoElement>;
  @ViewChild('cameraFeedback') feedback!: ElementRef<HTMLCanvasElement>;

  constructor(private imageCaptureService: ImageCapture) { }

}

in image-scanner. component i need to pass to injected object ImageCapture few constructor parameters one is SDK instance that is being imported and second two parameters are HTML DOM elements that I'm getting using @ViewChild decorator.

How can I achieve this?

Andrew
  • 1,507
  • 1
  • 22
  • 42

1 Answers1

1

You cannot pass paramaters to the constructor of the service, because your service is created on loading of the application. So when you use your service inside a component, the service is already instantiated.

A solution is to create a function in your service:

public initialize(sdk: any,videoSource: HTMLVideoElement,cameraFeedback: HTMLCanvasElement) {}

then you juste have to call this function, in the constructor of your component.

Soukyone
  • 568
  • 2
  • 13
  • ok, thanks but does `useFactory` in the providers solve this issue? Where I can directly create a constructor with parameters? – Andrew Feb 09 '21 at 10:07
  • @Andrew I think you can use `@Input` to pass objects to one component to another. – Srijon Chakraborty Feb 09 '21 at 10:10
  • @Andrew useFactory will not help you, beacause you need to pass some parameters, that are available after your component initialization (ViewChild). When you provide a service directly on your component, you have to do it on the '@Component' decorator, so properties of your component are not available. – Soukyone Feb 09 '21 at 10:14
  • @Soukyone but besides HTML elements, if I need to pass another object is it doable? – Andrew Feb 09 '21 at 10:17