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?

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

ok, thanks but does useFactory in the providers solve this issue? Where I can directly create a constructor with parameters?
@Andrew I think you can use @Input to pass objects to one component to another.
@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 but besides HTML elements, if I need to pass another object is it doable?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.