Laurens Wolf
Laurens Wolf

Reputation: 39

Csv Reader Typescript

I'm trying to build a simple csv reader for our project. first i builded one in JS and it worked fine, but i have difficulties converting it to ts.

this is the simple html code:

<div id="dvImportSegments" class="fileupload">
    <fieldset>
        <legend>Upload your CSV File</legend>
        <input type="file" name="File Upload" id="txtFileUpload" (change)="changeListener($event)" accept=".csv"/>
    </fieldset>
</div>

and this is the typescript that run on it:

import {Component, ViewEncapsulation} from 'angular2/core';
import {Router} from 'angular2/router';
import {ContentService} from "../service/contentService";
import {RouteParams} from "angular2/router";

@Component({
    selector: 'createCsv',
    templateUrl: 'app/partials_html/createCsv.component.html',
    encapsulation: ViewEncapsulation.None
})
export class CreateCsvComponent {

changeListener($event):void {
    this.upload($event.target);
}

upload(inputValue:any):void {

        var data = null;
        var file:File = inputValue.files[0];
        var reader:FileReader = new FileReader();

        //reader.readAsText(file);

        reader.onloadend = function (e) {
            var csvData = reader.result;
            data = $.csv.toArrays(csvData); //???

            if (data && data.length > 0) {
                alert('Imported -' + data.length + '- rows successfully!');
            } else {
                alert('No data to import!');
            }
        };

        reader.onerror = function () {
            alert('Unable to read ' + file);
        };
    }
//}
}

but i have some errors, data = $.csv.toArrays(csvData); //??? he cannot find the $ sign in there, how can i adress that?

Thanks in advance

Upvotes: 2

Views: 4987

Answers (1)

basarat
basarat

Reputation: 276057

he cannot find the $ sign in there

You are probably using https://github.com/evanplaice/jquery-csv

You need a TypeScript declaration file for JavaScript libraries that are not a part of your code base. A simple one vendor.d.ts:

declare var $:any;

Also you need to look at your module loader to make sure that the desired libraries are loaded before you code runs.

More

Some docs on declaration files and migrating : https://basarat.gitbooks.io/typescript/content/docs/types/migrating.html

Upvotes: 2

Related Questions