Angular 4:TypeError:this.function不是函数

时间:2018-06-04 23:17:03

标签: javascript angular typescript canvas

我没有想法..我看到这个问题被多次询问herehere以及更多,但我找不到解决问题的方法。据我所知,问题是this它没有引用正确的上下文。如何使用箭头函数从声明站点捕获this

drawImageProp(ctx, img, x, y, w, h, offsetX, offsetY) {
    // more code than displayed here
    ctx.drawImage(img, cx, cy, cw, ch, x, y, w, h);
}

onFileSelected(event) {
    for (const file of event.target.files) {
        if (file) {
            const reader = new FileReader();

            reader.onload = function(e: FileReaderEvent) {
                const canvas = <HTMLCanvasElement>document.getElementById('canvas');
                const ctx = canvas.getContext('2d');
                const img = new Image;

                img.onload = draw;

                function draw() {
                    this.drawImageProp(ctx, this, 0, 0, canvas.width, canvas.height, 0.5, 0.5);
                }

                img.src = e.target.result;
            };

            reader.readAsDataURL(file);
        }
    }
}

1 个答案:

答案 0 :(得分:1)

使用闭包:

onFileSelected(event) {
    const self = this;
    for (const file of event.target.files) {
        if (file) {
            const reader = new FileReader();

            reader.onload = function(e: FileReaderEvent) {
                const canvas = <HTMLCanvasElement>document.getElementById('canvas');
                const ctx = canvas.getContext('2d');
                const img = new Image;

                img.onload = draw;

                function draw() {
                    self.drawImageProp(ctx, img, 0, 0, canvas.width, canvas.height, 0.5, 0.5);
                }

                img.src = e.target.result;
            };

            reader.readAsDataURL(file);
        }
    }
}