Angular Newbie:调试Typescript错误"' imageLoader'的所有声明必须具有相同的类型参数"

时间:2017-06-23 22:04:28

标签: javascript angular typescript

我试图找出一些Angular 2的基础知识。我了解到脚本标签只能在index.html中使用,所以我试图在app.component.ts的组件类中将我的一个js文件翻译成ts。我真的很感激你能给予的任何帮助。

您能帮我理解并解决TS翻译错误吗?

以下是原始JavaScript:

var imageLoader = document.getElementById('imageLoader');
imageLoader.addEventListener('change', handleImage, false);
var canvas = document.getElementById('imageCanvas');
var ctx = canvas.getContext('2d');


function handleImage(e) {
    var reader = new FileReader();
    reader.onload = function (event) {
        var img = new Image();
        img.onload = function () {
            canvas.width = img.width;
            canvas.height = img.height;
            ctx.drawImage(img, 0, 0);
        }
        img.src = event.target.result;
    }
    reader.readAsDataURL(e.target.files[0]);
}

这是我当前的TypeScript,包括报告的错误:

Image detailing current TypeScript translation progress as well as VS Code reported errors

app.component.html:

<div ng-controller="AppController">
    <label>Image File:</label><br/>
    <input type="file" id="imageLoader" name="imageLoader" />
    <canvas id="imageCanvas"></canvas>
</div>

1 个答案:

答案 0 :(得分:1)

这将是适当的角度2版本:

import{ Component } from "@angular/core";

@Component({
selector: 'pc-app',

templateUrl: './app/app.component.html',
styleUrls: ['./app/app.component.css']

})

export class AppComponent {
    title: string = 'POSTERIZER';

    handleImage(e:any) {
        let imageLoader = document.getElementById('imageLoader');
        let canvas: any = document.getElementById('imageCanvas');
        let ctx = canvas.getContext('2d');
        var reader = new FileReader();
        reader.onload = function (event:any) {
            var img = new Image();
            img.onload = function () {
                canvas.setAttribute('width', '599');
                canvas.setAttribute('height', '599');
                ctx.drawImage(img, 0, 0);
            }
            img.src = event.target.result;
        }
        reader.readAsDataURL(e.target.files[0]);
    }

}