2017-02-04 47 views
0

我使用Angular 2 + Angular CLI構建應用程序。我發現這個很酷的圖書館'csvtojson',正是我想要的基於演示 所以我試圖將其納入我的項目。但是,我的第一個問題是,是否有可能將這個庫包含在我的項目中,因爲我沒有看到它是爲Angular 2構建的? 如果沒有......那是否意味着我只能簡單地看向別處,感到難過?使用Angular 2的外部庫

如果是...我將如何實現它。我已經做了以下不工作

1. npm i --save csvtojson 
2. inside app.module.ts 
    import { csvtojson } from 'csvtojson' 
    providers: [ 
     {{...}} 
     csvtojson //test 
    ], 

3. app.component.ts 
    import { csvtojson } from 'csvtojson' 
    constructor(private csvToJson: csvtojson) { } 
    this.csvToJson.csv({ noheader: true }) 
     .fromString(data) 
     .on('csv', (csvRow) => { // this func will be called 3 times 
      console.log('afasf',csvRow) // => [1,2,3] , [4,5,6] , [7,8,9] 
     }) 
     .on('done',() => { 
      //parsing finished 
     }) 

而且我得到這個錯誤

ERROR in ./~/csvtojson/libs/core/workerMgr.js Module not found: Error: Can't resolve 'child_process' in '/Users/james/Desktop/web-app/nod e_modules/csvtojson/libs/core'

回答

0

因爲這個庫需要節點服務器上運行,你不能在瀏覽器child_process

的瀏覽器,該解決方案可以幫助你https://www.bennadel.com/blog/1504-ask-ben-parsing-csv-strings-with-javascript-exec-regular-expression-command.htm

+0

工作Plunker這是否意味着這個庫只是我夠不着的地方? – user172902

+0

對於瀏覽器,您可以使用此解決方案https://www.bennadel.com/blog/1504-ask-ben-parsing-csv-strings-with-javascript-exec-regular-expression-command.htm –

0

無需外部庫。

這裏csvTOjson

import {Component, NgModule} from '@angular/core' 
    import {BrowserModule} from '@angular/platform-browser' 

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

    @Component({ 
     selector: 'my-app', 
     templateUrl: './app.html' 
    }) 
    export class AppComponent { 
     title = 'csvTOjson works!'; 
     text : any ; 
     JSONData : any; 
     csvJSON(csvText) { 
     var lines = csvText.split("\n"); 

     var result = []; 

     var headers = lines[0].split(","); 
     console.log(headers); 
     for (var i = 1; i < lines.length-1; i++) { 

      var obj = {}; 
      var currentline = lines[i].split(","); 

      for (var j = 0; j < headers.length; j++) { 
       obj[headers[j]] = currentline[j]; 
      } 

      result.push(obj); 

     } 

     //return result; //JavaScript object 
     console.log(JSON.stringify(result)); //JSON 
     this.JSONData = JSON.stringify(result); 
    } 

    convertFile(input) { 

    const reader = new FileReader(); 
    reader.readAsText(input.files[0]); 
    reader.onload =() => { 
     let text = reader.result; 
     this.text = text; 
     console.log(text); 
     this.csvJSON(text); 
    }; 

    } 
    } 


    @NgModule({ 
     imports: [ BrowserModule ], 
     declarations: [ AppComponent ], 
     bootstrap: [ AppComponent ] 
    }) 
    export class AppModule {}