html2canvas in angular 4

Pein picture Pein · May 20, 2017 · Viewed 25.9k times · Source

I am able to take a screenshot using html2canvas in angular 4 but i need to send the string image to the server side using a http post call

Component

Service that i am calling to do a post

 addCanvasResource(body: Object): Observable<any> {
        let bodyString = JSON.stringify(body);
        let headers = new Headers({ 'Content-Type': 'application/json' });
        let options = new RequestOptions({ headers: headers });

        return this.http.post(this.baseUrl + 'api/v3/images/AddCanvasImage', body, options)
            .map((response: Response) => {
                if (response.status < 200 || response.status >= 300) {
                    throw new Error('This request has failed ' + response.status);
                }
                else {
                    return response;
                }
            });
    }  

I am unable to access AddImagesResource() function in html2canvas enter image description here

can you please tell me how to achieve the above functionality

Answer

Daniel Galarza picture Daniel Galarza · May 30, 2017

When providing the callback for a promise in Angular, you should use an arrow function, rather than an anonymous function. Arrow functions bind to the current context correctly, so the function you are trying to call will be accessible.

Try this instead:

pdfDownload() {
    html2canvas(document.body).then(canvas => {
        var imgData = canvas.toDataURL("image/png");
        this.AddImagesResource(imgData);
        document.body.appendChild(canvas);
    });
}