Home > Blockchain >  Angular pass a method to a service
Angular pass a method to a service

Time:10-26

I am using Angular 12 and I have a method that takes a screenshot of an element. It works, but I want to call it from a service.

Here is the code:

import html2canvas from 'html2canvas';
import { saveAs } from 'file-saver';

...

takesshotOfElement(elementId: any) {
    const element = document.getElementById(elementId) as HTMLCanvasElement;
    html2canvas(element).then((canvas) => {
      canvas.toBlob((blob: any) => {
        saveAs(blob, "filename.png");
      });
    });    
}

How do I go with putting this method in a service so I can call the service instead and make the method cleaner?

CodePudding user response:

You can create a service and add this method. Now, the processing for screenshot might take time and you don't want the main thread to wait for it, so make it async and return the promise from the method.

takesshotOfElement(elementId: any) {
    const element = document.getElementById(elementId) as HTMLCanvasElement;

    return new Promise( async (resolve, reject) => {
          try {
             const canvas = await html2canvas(element);
                   canvas.toBlob((blob: any) => {
                   saveAs(blob, "filename.png");
                   // once the things are done
                   resolve('Blob is completed');
             });  
          } catch (e){
             reject(e);
          }
    })   
}

The component where you want to call it, you can use async/await or then/catch. This way whenever you call this method, it will update the things based on the processing done for snapshot.

CodePudding user response:

I've created a sample service snippet below:

import { Injectable, Inject } from '@angular/core';
import { DOCUMENT } from '@angular/common';
import html2canvas from 'html2canvas';
import { saveAs } from 'file-saver';

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

  constructor(
    @Inject(DOCUMENT) private document
  ) { }

  takesshotOfElement(elementId: any) {
    const element = this.document.getElementById(elementId) as HTMLCanvasElement;
    html2canvas(element).then((canvas) => {
      canvas.toBlob((blob: any) => {
        saveAs(blob, "filename.png");
      });
    });
  }
}

You can invoke this service in component as below:

constructor(
    private serivce: DummyService
  ) {

  }

  ngOnInit() { //or in any method you want
    this.serivce.takesshotOfElement('test');
  }
  • Related