我可以使用角度4中的html2canvas截取屏幕截图,但我需要使用http post post将字符串图像发送到服务器端
组件
import { Component, OnInit, NgZone } from '@angular/core';
import { Router, ActivatedRoute, Params } from '@angular/router';
import { EventsEmitter } from '../../assets/scripts/services/eventsEmitter';
import { WindowRef } from '../../assets/scripts/services/window';
import { ImagesService } from '../images/images.component.service';
import { DomSanitizer } from '@angular/platform-browser';
import * as html2canvas from "html2canvas";
@Component({
selector: 'categories',
templateUrl: 'app/components/view/view.component.html',
styleUrls: ['app/components/view/view.component.css'],
providers: [ImagesService]
})
export class ViewComponent {
constructor(
private route: ActivatedRoute,
private router: Router,
private imagesService: ImagesService,
private eventsEmitter: EventsEmitter
private sanitizer: DomSanitizer,
private window: WindowRef) {
this.window.nativeWindow.scrollTo(0, 0);
}
ngOnInit() {
}
pdfDownload() {
html2canvas(document.body).then(function (canvas) {
var imgData = canvas.toDataURL("image/png");
document.body.appendChild(canvas);
});
}
AddImagesResource(query: any) {
this.imagesService.addCanvasResource(query)
.subscribe(response => {
this.eventsEmitter.broadcast('Success', 'Changes Saved Succesfully');
},
error => {
this.eventsEmitter.broadcast('Error', 'Error Occured');
});
}
}
<a data-html2canvas-ignore (click)="pdfDownload()">screenshot</a>
我打电话做的服务
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;
}
});
}
我无法访问html2canvas 中的AddImagesResource()函数
您能否告诉我如何实现上述功能
答案 0 :(得分:5)
在Angular中为promise提供回调时,您应该使用arrow function而不是匿名函数。箭头函数正确绑定到当前上下文,因此您可以访问您尝试调用的函数。
请改为尝试:
pdfDownload() {
html2canvas(document.body).then(canvas => {
var imgData = canvas.toDataURL("image/png");
this.AddImagesResource(imgData);
document.body.appendChild(canvas);
});
}
答案 1 :(得分:1)
pdfDownload() {
let self = this;//use this variable to access your class members inside then().
html2canvas(document.body).then(canvas => {
var imgData = canvas.toDataURL("image/png");
self.AddImagesResource(imgData);
document.body.appendChild(canvas);
});
}
答案 2 :(得分:0)
确保将脚本导入angular-cli.json中的脚本列表下
"scripts": [
"../node_modules/html2canvas/dist/html2canvas.min.js"
]
在课堂上为:
import * as html2canvas from "html2canvas"